0% found this document useful (0 votes)
4 views22 pages

Introduction To Java Programming

Uploaded by

bonassengabo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views22 pages

Introduction To Java Programming

Uploaded by

bonassengabo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Introduction to Java Programming

1. Introduction to Java ............................................................................ 3


2. Features of Java ................................................................................... 3
3. History of Java..................................................................................... 4
4. Object-Oriented Programming with Java .............................................. 4
4.1Encapsulation ......................................................................................... 4
4.2Inheritance .............................................................................................. 4
4.3Polymorphism ......................................................................................... 5
5.Tools You Will Need............................................................................... 5
6. Setting up your Java development environment................................... 5
6.1 What is JVM? ......................................................................................... 5
6.2 What is JRE? .......................................................................................... 5
6.3 What is JDK? ......................................................................................... 6
7. Java comments .................................................................................... 6
8.Data types in Java ................................................................................ 6
9.Use of operators in Java ........................................................................ 7
9.1 Arithmetic Operators .............................................................................. 7
9.2 Relational operators................................................................................ 7
9.3 Logical operators/Boolean operators ....................................................... 7
9.4 Assignment operators ............................................................................. 7
10.Variablesin Java .................................................................................. 8
Scope of a variable .................................................................................. 8
10.1 Local variables ...................................................................................... 8
10.2 Global variables .................................................................................... 8
11.Conditions in Java .............................................................................. 8
11.1Java if Statement ................................................................................... 8
11.2Java if...else Statement .......................................................................... 8
11.3 Java nested/ladder if..else Statement ................................................... 9
11.4 Java switch Statement ........................................................................ 10
12.Java loops ......................................................................................... 11
12.1 Java for Loop ...................................................................................... 11
12.2 Infinite for Loop .................................................................................. 12
12.3 Java while and do...while Loop ........................................................... 12
1|Page
12.4 Java do...while Loop ........................................................................... 13
12.5 Java break Statement ......................................................................... 13
12.6 Java continue Statement .................................................................... 14
13.Java Arrays ....................................................................................... 15
14. IO streams in Java ........................................................................... 15
14.1 Java Output ....................................................................................... 15
14.2 Java Input .......................................................................................... 16
14.3 Readers in Java .................................................................................. 16
14.3.1 Java Buffered Readers & Input Stream Readers ............................ 16
15.FileStreams ....................................................................................... 17
15.1 FileInputStream Class ........................................................................ 17
15.2 Understanding the FileOutputStreamClas .......................................... 17
15.3 Java File Reader ................................................................................. 18
16. OOP and Java ................................................................................... 18
16.1 Introduction to OOP in Java ............................................................... 18
16.2 Object in Java (OOP) ........................................................................... 19
16.3 Class in Java (OOP) ............................................................................ 19
16.4 Constructor in Java ............................................................................ 19
16.5 Abstraction ......................................................................................... 20
16.6 Encapsulation .................................................................................... 20
16.7 Inheritance in Java ............................................................................. 21
16.8 Polymorphism .................................................................................... 22

2|Page
1. Introduction to Java
Java is an object-oriented programming language originally developed by Sun
Microsystems which was initiated by James Gosling and released in 1995 as
core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the
advancement of Java and its widespread popularity, multiple configurations
were built to suit various types of platforms. For example: J2EE for Enterprise
Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME
respectively. Java is guaranteed to be Write Once, Run Anywhere.

2. Features of Java
Java is:
 Object-Oriented programming language
In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
 Platform Independent
Unlike many other programming languages including C and C++, when
Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over
the web and interpreted by the Virtual Machine (JVM) on whichever
platform it is being run on.
 Simple
Java is designed to be easy to learn. If you understand the basic concept
of OOP Java, it would be easy to master.
 Secure
With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
 Architecture-neutral
Java compiler generates an architecture-neutral object file format, which
makes the compiled code executable on many processors, with the
presence of Java runtime system.
 Portable
Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is
written in ANSI C with a clean portability boundary, which is a POSIX
subset.
 Robust
Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.
 Multithreaded
With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the
developers to construct interactive applications that can run smoothly.

3|Page
 Interpreted
Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and
analytical since the linking is an incremental and light-weight process.
 High Performance
With the use of Just-In-Time compilers, Java enables high performance.
 Distributed
Java is designed for the distributed environment of the internet.

 Dynamic
Java is considered to be more dynamic than C or C++ since it is designed
to adapt to an evolving environment. Java programs can carry extensive
amount of run-time information that can be used to verify and resolve
accesses to objects on run-time.

3. History of Java
 James Gosling initiated Java language project in June 1991 for use in
one of his many set-top box projects.
 The language, initially called ‘Oak’ after an oak tree that stood outside
Gosling's office, also went by the name ‘Green’ and ended up later being
renamed as Java, from a list of random words.
 Sun released the first public implementation as Java 1.0 in 1995. It
promised Write Once, Run Anywhere (WORA), providing no-cost run-
times on popular platforms.
 On 13 November, 2006, Sun released much of Java as free and open
source software under the terms of the GNU General Public License
(GPL).
 On 8 May, 2007, Sun finished the process, making all of Java's core code
free and open-source, aside from a small portion of code to which Sun
did not hold the copyright.

4. Object-Oriented Programming with Java


4.1Encapsulation
Encapsulation is the process of combining data and functions into a single unit
called class. Using the method of encapsulation, the programmer cannot
directly access the data.
Data is only accessed through the functions present inside the class. Data
encapsulation led to the important concept of data hiding.
4.2Inheritance
Inheritance is the process by which new classes called ―derived classesare
created from existing classes called ―base classes. Derived classes have all the
features of the base class and the programmer can choose to add new features
specific to the newly created class. For example, a programmer can create a
base class named Shape and define derived classes as Circle, Triangle,
Rectangle, etc. Each of these derived classes (circle, triangle, rectangle, etc) has

4|Page
all features of the base class (Shape) with additional features specific to them;
circle would have its own defined features, triangle would have its own defined
features, rectangle would have its own defined features, etc. With inheritance,
programmers save time during program development by reusing proven and
debugged high-quality software. This also increases the likelihood that a
system will be implemented effectively.
4.3Polymorphism
Polymorphism is the ability to use a function in different ways. Poly means
many and morph means forms. Polymorphism refers to the same name taking
many forms.

5.Tools You Will Need


For performing the examples discussed in this tutorial, you will need a Pentium
200-MHz computer with a minimum of 64 MB of RAM (128 MB of RAM
recommended).
You will also need the following softwares:
 Linux 7.1 or Windows xp/7/8 operating system
 Java JDK 8
 Notepad/Wordpad/Eclipse/Jcreator/Netbeans or any other text editor

6. Setting up your Java development environment


Although you can use these tools to develop your applications, most developers
appreciate the additional functionality, task management, and visual interface
of an IDE.
The JDK includes a set of command-line tools for compiling and running your
Java code, including a complete copy of the JRE.
6.1 What is JVM?
JVM (Java Virtual Machine) is an abstract machine that enables your
computer to run a Java program.
When you run the Java program, Java compiler first compiles your Java code
to bytecode. Then, the JVM translates bytecode into native machine code (set of
instructions that a computer's CPU executes directly).
Java is a platform-independent language - It's because when you write Java
code, it's ultimately written for JVM but not your physical machine (computer).
Since, JVM executes the Java bytecode which is platform independent, Java is
platform-independent.

6.2 What is JRE?


JRE (Java Realtime Environment) is a software package that provides Java
class libraries, along with Java Virtual Machine (JVM), and other components
to run applications written in Java programming. JRE is the superset of JVM.

5|Page
6.3 What is JDK?
JDK (Java Development Kit) is a software development kit to develop
applications in Java. When you download JDK, JRE is also downloaded, and
don't need to download it separately. In addition to JRE, JDK also contains
number of development tools (compilers, JavaDoc, Java Debugger etc).

Relationship between JVM, JRE, and JDK

You First Java Program


Java "Hello, World!" Program
classHelloWorld{
publicstaticvoid main(String[]args){
System.out.println("Hello, World!");
}
}
OUTPUT: Hello, World!

7. Java comments
In Java programming language, there are two types of comments:
/* ... */ : Block comment
// .... : Line comment

8.Data types in Java


Data type play an important role in a program because they tell the computer
what kind of data you are referring to.

6|Page
Here are some data types used in Java:
Name Description Size Range
short Short integer 2 bytes -32768 to 32767
int
int Integer 4 bytes -2147483648 to
2147483647
float Floating point number 4 bytes +/- 3.4e +/- 38 (~7
digits)
double Double precision floating 8 bytes +/- 1.7e +/- 308 (~15
point number digits)
bool Boolean value can take one 1 byte true or false
of two numbers: True or
False
char Character 1 byte characters

9.Use of operators in Java


9.1 Arithmetic Operators
The arithmetic operators can be used more times in one expression. In such a
case, you can express priority of operations by parentheses. (),*,/,%,+,-
̶ Addition (+) : Used to sum the values of two expressions
̶ Subtraction (-) : Used to subtract a numeric data from
another
̶ Multiplication (*) : Used to multiply two numeric data types
̶ Division (/) : Used to divide two numeric data types
̶ Modulus (%) : It returns the remainder of division
9.2 Relational operators
̶ Greater than : >
̶ Greater than or equal to : >=
̶ Less than : <
̶ Less than or equal to : <=
̶ Equal to : ==
̶ Not equal to : !=
9.3 Logical operators/Boolean operators
Logical AND : &&
Logical OR : ||
Logical NOT : !
9.4 Assignment operators
= : Assignment
+= : Addition and assignment
-= : Subtraction and assignment
*= : Multiplication and assignment
/= : Division and assignment
%= : Modulo and assignment
>>= : Right shift and assignment

7|Page
<<= : Left shift and assignment
&= : Bitwise AND and assignment
^= : Bitwise NOT and assignment
|= : Bitwise OR and assignment

10.Variablesin Java
A variable is a memory zone which is used to store data. It is characterized by a
name, an address and a data type.
Syntax to declare variables
A variable to be used must first be declared. While declaring a variable, you
must include the data type along with the name of the variable.
syntax:<variable type><name of variable>;
Here are some variable declaration examples:
int x;
double a, b, c, d;
Scope of a variable
10.1 Local variables
Variables defined inside a function are local (internal) to the function they are
declared, and called automatic variables.
10.2 Global variables
Variables that are both alive and active throughout the entire program are
called as external variables. They are also called global variables; they can be
accessed by any function in a program.

11.Conditions in Java
11.1Java if Statement
Syntax:
if (expression) {
// statements
}
Example:
classIfStatement{
publicstaticvoid main(String[]args){
int number =10;
if(number >0){
System.out.println("Number is positive.");
}
}
}
OUTPUT: Number is positive.
11.2Java if...else Statement
The if statement executes a certain section of code if the test expression is
evaluated to true. The if statement can have optional else statement.
Syntax:
if (expression) {
8|Page
// codes
}
else {
// some other code
}

Example:
//Check whether a number is even or odd
importjava.util.Scanner;
publicclassEvenOdd{
publicstaticvoid main(String[]args){
Scanner reader =newScanner(System.in);
System.out.print("Enter a number: ");
intnum=reader.nextInt();
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
OUTPUT:Enter a number: 12
12 is even
11.3 Java nested/ladder if..else Statement
Syntax:
if (expression1)
{
// codes
}
else if(expression2)
{
// codes
}
else if (expression3)
{
// codes
}
.
.
else
{
// codes
}

9|Page
Example:
classLadder{
publicstaticvoid main(String[]args){
int number =0;
if(number >0){
System.out.println("Number is positive.");
}
elseif(number <0){
System.out.println("Number is negative.");
}
else{
System.out.println("Number is 0.");
}
}
}
OUTPUT:Number is 0.
11.4 Java switch Statement
In Java, the switch statement can a substitute for long if..else..if ladders which
generally makes your code more readable.

Syntax:
switch (variable/expression) {
case value1:
// statements
break;
case value2:
// statements
break;
.. .. ...
.. .. ...
default:
// statements
}
Example:
classDay{
public static void main(String[]args){
int week =4;
String day;
switch(week){
case1:
day="Sunday";
break;
case2:
day="Monday";

10 | P a g e
break;
case3:
day="Tuesday";
break;
case4:
day="Wednesday";
break;
case5:
day="Thursday";
break;
case6:
day="Friday";
break;
case7:
day="Saturday";
break;
default:
day="Invalid day";
break;
}
System.out.println(day);
}
}
OUTPUT: Wednesday

12.Java loops
12.1 Java for Loop
Loop is used in programming to repeat a specific block of code until certain
condition is met (test expression is false).
Syntax:
for (initialization; testExpression; update)
{
// codes inside for loop's body
}
Example:
// Program to print a sentence 3 times
classLoop{
publicstaticvoid main(String[]args){
for(inti=1;i<=3;++i){
System.out.println("Line "+i);
}
}
}

11 | P a g e
OUTPUT:
Line 1
Line 2
Line 3
12.2 Infinite for Loop
If the test expression is never false, for loop will run forever. This is called
infinite for loop. Let's take an example:
Example:
// Infinite for Loop
classInfinite{
publicstaticvoid main(String[]args){
int sum =0;
for(inti=1;i<=10;--i){
System.out.println("Hello");
}
}
}
Here, the test expression i<= 10 is never false and hello is printed infinite
number to times (at least in theory).
The initialization, update and test expression used in for statement is optional.
Here's an another example of infinite for loop.
for(;;){

}
12.3 Java while and do...while Loop
Syntax:
while (testExpression) {
// codes inside body of while loop
}
Example:
// Program to print line 3 times
classLoop{
publicstaticvoid main(String[]args){
inti=1;
while(i<=3){
System.out.println("Line "+i);
++i;
}
}
}
OUTPUT:
Line 1
Line 2
12 | P a g e
Line 3
12.4 Java do...while Loop
The do...while loop is similar to while loop with one key difference. The body of
do...while loop is executed for once before the test expression is checked.

Syntax:
do {
// codes inside body of do while loop
} while (testExpression);
Example:
/* calculatation the sum of numbers entered by the user until user enters 0 */
importjava.util.Scanner;
classSum{
publicstaticvoid main(String[]args){
double number, sum =0.0;
Scanner input =newScanner(System.in);
do{
System.out.print("Enter a number: ");
number=input.nextDouble();
sum+= number;
}while(number !=0.0);
System.out.println("Sum = "+ sum);
}
}
OUTPUT:
Enter a number: 2.5
Enter a number: 23.3
Enter a number: 0
Sum = 25.0
12.5 Java break Statement
The break statement terminates the loop immediately, and the control of the
program moves to the next statement following the loop.
Syntax:
break;
Example:
The program below calculates the sum of numbers entered by the user until
user enters a negative number.
importjava.util.Scanner;
classUserInputSum{
publicstaticvoid main(String[]args){
Double number, sum =0.0;
Scanner input =newScanner(System.in);
while(true){
System.out.print("Enter a number: ");
number=input.nextDouble();
13 | P a g e
if(number <0.0){
break;
}
sum+= number;
}
System.out.println("Sum = "+ sum);
}
}

OUTPUT:
Enter a number: 3.2
Enter a number: 5
Enter a number: -4.5
Sum = 3.3
12.6 Java continue Statement
The continue statement skips the current iteration of a loop (for, while, and
do...while loop).
Syntax:
continue;
Example:
The program below calculates the sum of maximum of 5 positive numbers
entered by the user. If the user enters negative number or zero, it is skipped
from calculation.
importjava.util.Scanner;
classAssignmentOperator{
publicstaticvoid main(String[]args){
Double number, sum =0.0;
Scanner input =newScanner(System.in);
for(inti=1;i<6;++i){
System.out.print("Enter a number: ");
number=input.nextDouble();
if(number <=0.0){
continue;
}
sum+= number;
}
System.out.println("Sum = "+ sum);
}
}
OUTPUT:
Enter a number: 2.2
Enter a number: 5.6
Enter a number: -3
Sum = 5.8

14 | P a g e
13.Java Arrays
An array is a container that holds data (values) of one single type. For example,
you can create an array that can hold 100 values of int type.
How to declare an array?
Syntax: dataType[ ] arrayName;
Let's take another example:
int[] age;
age = new int[5];

Example:
importjava.util.Scanner;
public class Array_Sum
{
public static void main(String[] args)
{
int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(inti = 0; i< n; i++)
{
a[i] = s.nextInt();
sum = sum + a[i];
}
System.out.println("Sum:"+sum);
}
}

14. IO streams in Java


A stream can be defined as a sequence of data. There are two kinds of Streams:
InPutStream used to read data from a source, and OutPutStream used for
writing data to a destination.
14.1 Java Output
You can simply use System.out.println(), System.out.print() or
System.out.printf() to send output to standard output (screen).
Example:
classAssignmentOperator{
publicstaticvoid main(String[]args){

System.out.println("Java programming is interesting.");


}
}
OUTPUT: Java programming is interesting.

15 | P a g e
14.2 Java Input
There are several ways to get input from the user in Java. For that, you need to
import Scanner class using:
importjava.util.Scanner;
Example:
importjava.util.Scanner;
classInput{
publicstaticvoid main(String[]args){
Scanner input =newScanner(System.in);
System.out.print("Enter an integer: ");
int number =input.nextInt();
System.out.println("You entered "+ number);
}
}
OUTPUT:
Enter an integer: 23
You entered 23
14.3 Readers in Java
14.3.1 Java Buffered Readers & Input Stream Readers
In Java, there are multiple ways to obtain user input from the keyboard. One of
the objects that could get the job done is a Buffered Reader using the
readlinemethod, along with an Input Stream Reader.
Example - Getting a string from the user
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
public class BufferedReaderExample {
public static void main(String[]args)throws IOException{
InputStreamReader ISR = new InputStreamReader(System.in);
BufferedReader BR = new BufferedReader(ISR);
System.out.println("What's your name?");
String userInput = BR.readLine(); //program waits here until the user
inserts a line of text
System.out.println("Your name is : "+userInput);
BR.close();
ISR.close();
}
}
OUTPUT:
What's your name?
Jack Something
Your name is : Jack Something

16 | P a g e
15.FileStreams
15.1 FileInputStream Class
The FileInputStream is a byte input stream class that provides methods for
reading bytes from a file. We can create an instance of this class by supplying a
File or a path name, using these two constructors:
 FileInputStream(File file)
 FileInputStream(String name)
15.2 Understanding the FileOutputStreamClas
The FileOutputStream is a byte output stream class that provides methods for
writing bytes to a file. We can create an instance of this class by supplying a
File or a path name, and/or specify to overwrite or append to an existing file,
using the following constructors:
 FileOutputStream(File file)
 FileOutputStream(File file, boolean append)
FileInputStream and FileOutputStream Examples
Example: Copy a File
import java.io.*;

public class CopyFile {


private static final int BUFFER_SIZE = 4096;

public static void main(String[] args) {


if (args.length< 2) {
System.out.println("Please provide input and output files");
System.exit(0);
}
String inputFile = args[0];
String outputFile = args[1];

try (
InputStreaminputStream = new FileInputStream(inputFile);
OutputStreamoutputStream = new FileOutputStream(outputFile);
){
byte[] buffer = new byte[BUFFER_SIZE];
intbytesRead = -1;

while ((bytesRead = inputStream.read(buffer)) != -1) {


outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

17 | P a g e
15.3 Java File Reader
FileReader is used for reading streams of characters.
Following is an example to demonstrate class −
import java.io.*;
publicclassFileRead{

publicstaticvoid main(Stringargs[])throwsIOException{
Filefile=newFile("Hello1.txt");

// creates the file


file.createNewFile();

// creates a FileWriter Object


FileWriter writer =newFileWriter(file);

// Writes the content to the file


writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();

// Creates a FileReader Object


FileReaderfr=newFileReader(file);
char[] a =newchar[50];
fr.read(a);// reads the content to the array

for(char c : a)
System.out.print(c);// prints the characters one by one
fr.close();
}
}
Output:
This
is
an
example

16. OOP and Java


16.1 Introduction to OOP in Java
Object-oriented programming System (OOPs) is a programming paradigm based
on the concept of “objects” that contain data and methods.
Object oriented programming brings together data and its behavior (methods)
in a single location (object) makes it easier to understand how a program works.

18 | P a g e
16.2 Object in Java (OOP)
Object: is a bundle of data and its behavior (often known as methods).
Objects have two characteristics: They have states and behaviors.
Examples of states and behaviors:
Object: House
State: Address, Color, Area
Behavior: Open door, close door
16.3 Class in Java (OOP)
A class can be considered as a blueprint using which you can create as many
objects as you like. For example, here we have a class Website that has two
data members (also known as fields, instance variables and object states), as
follows:
public class Website {
//fields (or instance variable)
String webName;
intwebAge;

// constructor
Website(String name, int age){
this.webName = name;
this.webAge = age;
}
public static void main(String args[]){
//Creating objects
Website obj1 = new Website("beginnersbook", 5);
Website obj2 = new Website("google", 18);

//Accessing object data through reference


System.out.println(obj1.webName+" "+obj1.webAge);
System.out.println(obj2.webName+" "+obj2.webAge);
}
}
Output:
beginnersbook 5
google 18
16.4 Constructor in Java
Constructor looks like a method but it is in fact not a method. It’s name is
same as class name and it does not return any value. You must have seen this
statement in almost all the programs I have shared above:
MyClassobj=newMyClass();

19 | P a g e
Example of constructor:
publicclassConstructorExample{
int age;
String name;
//Default constructor
ConstructorExample(){
this.name="Chaitanya";
this.age=30;
}
//Parameterized constructor
ConstructorExample(Stringn,int a){
this.name=n;
this.age=a;
}
publicstaticvoid main(Stringargs[]){
ConstructorExample obj1 =newConstructorExample();
ConstructorExample obj2 =
newConstructorExample("Steve",56);
System.out.println(obj1.name+" "+obj1.age);
System.out.println(obj2.name+" "+obj2.age);
}
}
Output:
Chaitanya30
Steve56
16.5 Abstraction
Abstraction is a process where you show only “relevant” data and “hide”
unnecessary details of an object from the user. For example, when you login to
your bank account online, you enter your user_id and password and press
login, what happens when you press login, how the input data sent to server,
how it gets verified is all abstracted away from the you.
16.6 Encapsulation
Encapsulation simply means binding object state(fields) and behavior(methods)
together. If you are creating class, you are doing encapsulation.
Encapsulation example in Java:
classEmployeeCount
{
privateintnumOfEmployees=0;
publicvoidsetNoOfEmployees(int count)
{
numOfEmployees= count;
}
publicdoublegetNoOfEmployees()
{
returnnumOfEmployees;
20 | P a g e
}
}
publicclassEncapsulationExample
{
publicstaticvoid main(Stringargs[])
{
EmployeeCountobj=newEmployeeCount();
obj.setNoOfEmployees(5613);
System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees());
}
}
Output:
NoOfEmployees:5613
16.7 Inheritance in Java
The process by which one class acquires the properties and functionalities of
another class is called inheritance. Inheritance provides the idea of reusability
of code and each sub class defines only those features that are unique to it,
rest of the features can be inherited from the parent class.
Syntax:
To inherit a class we use extends keyword. Here class A is child class and class
B is parent class.
class A extends B
{
……………………………………….
}
Inheritance Example
classTeacher
{
String designation ="Teacher";
String college ="Beginnersbook";
void does()
{
System.out.println("Teaching");
}
}
publicclassMathTeacherextendsTeacher{
StringmainSubject="Maths";
publicstaticvoid main(Stringargs[]){
MathTeacherobj=newMathTeacher();
System.out.println(obj.college);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}

21 | P a g e
Output:
Beginnersbook
Teacher
Maths
Teaching
16.8 Polymorphism
Polymorphism is a object oriented programming feature that allows us to
perform a single action in different ways.
Polymorphism example:
classDisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, intnum)
{
System.out.println(c + " "+num);
}
}
public class ExampleOverloading
{
public static void main(String args[])
{
DisplayOverloadingobj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:
a
a 10

22 | P a g e

You might also like