Java Oops Concepts: Oops (Object Oriented Programming System)
Java Oops Concepts: Oops (Object Oriented Programming System)
Java Oops Concepts: Oops (Object Oriented Programming System)
In this page, we will learn about basics of OOPs. Object Oriented Programming is a paradigm that provides
many concepts such asinheritance, data binding, polymorphism etc.
Simula is considered as the first object-oriented programming language. The programming paradigm where
everything is represented as an object, is known as truly object-oriented programming language.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike
etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to convense
the customer differently, to draw something e.g. shape or rectangle etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we
don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.
Object based programming language follows all the features of OOPs except Inheritance. JavaScript and
VBScript are examples of object based programming languages.
Do You Know ?
Can we overload main method ?
Naming Convention
Constructor
static keyword
Inheritance
Aggregation
Method Overriding
super keyword
final keyword
Abstract class
Interface
Runtime Polymorphism
Package
Access Modifiers
Encapsulation
Object Cloning
Name Convention
class name should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener
etc.
method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(),
println() etc.
variable name should start with lowercase letter e.g. firstName, orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
If name is combined with two words, second word will start with uppercase letter always e.g.
actionPerformed(), firstName, ActionEvent, ActionListener etc.
2. Class in Java
6. Annonymous Object
In this page, we will learn about java objects and classes. In object-oriented programming technique, we
design a program using objects and classes.
Object is the physical as well as logical entity whereas class is the logical entity only.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It
can be physical or logical (tengible and intengible). The example of integible object is banking system.
behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible
to the external user. But,it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to
write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So
object is the instance(result) of a class.
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which objects
are created.
data member
method
constructor
block
1. class <class_name>{
2. data member;
3. method;
4. }
In this example, we have created a Student class that have two data members id and name. We are
creating the object of the Student class by new keyword and printing the objects value.
1. class Student1{
2. int id;//data member (also instance variable)
3. String name;//data member(also instance variable)
4.
5. public static void main(String args[]){
6. Student1 s1=new Student1();//creating an object of Student
7. System.out.println(s1.id);
8. System.out.println(s1.name);
9. }
10. }
Test it Now
Output:0 null
Instance variable in Java
A variable that is created inside the class but outside the method, is known as instance variable.Instance
variable doesn't get memory at compile time.It gets memory at runtime when object(instance) is
created.That is why, it is known as instance variable.
Method in Java
Advantage of Method
Code Reusability
Code Optimization
new keyword
In this example, we are creating the two objects of Student class and initializing the value to these
objects by invoking the insertRecord method on it. Here, we are displaying the state (data) of the objects
by invoking the displayInformation method.
1. class Student2{
2. int rollno;
3. String name;
4.
5. void insertRecord(int r, String n){ //method
6. rollno=r;
7. name=n;
8. }
9.
10. void displayInformation(){System.out.println(rollno+" "+name);}//method
11.
12. public static void main(String args[]){
13. Student2 s1=new Student2();
14. Student2 s2=new Student2();
15.
16. s1.insertRecord(111,"Karan");
17. s2.insertRecord(222,"Aryan");
18.
19. s1.displayInformation();
20. s2.displayInformation();
21.
22. }
23. }
Test it Now
111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference variable refers to the
object allocated in the Heap memory area. Here, s1 and s2 both are reference variables that refer to the
objects allocated in memory.
There is given another example that maintains the records of Rectangle class. Its exaplanation is same
as in the above Student class example.
1. class Rectangle{
2. int length;
3. int width;
4.
5. void insert(int l,int w){
6. length=l;
7. width=w;
8. }
9.
10. void calculateArea(){System.out.println(length*width);}
11.
12. public static void main(String args[]){
13. Rectangle r1=new Rectangle();
14. Rectangle r2=new Rectangle();
15.
16. r1.insert(11,5);
17. r2.insert(3,15);
18.
19. r1.calculateArea();
20. r2.calculateArea();
21. }
22. }
Output:55
45
By newInstance() method
By clone() method
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as annonymous object.
If you have to use an object only once, annonymous object is a good approach.
1. class Calculation{
2.
3. void fact(int n){
4. int fact=1;
5. for(int i=1;i<=n;i++){
6. fact=fact*i;
7. }
8. System.out.println("factorial is "+fact);
9. }
10.
11. public static void main(String args[]){
12. new Calculation().fact(5);//calling method with annonymous object
13. }
14. }
Output:Factorial is 120
Output:55
45
If a class have multiple methods by same name but different parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of the
program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to understand the behaviour of the method because
its name differs. So, we perform method overloading to figure out the program quickly.
In java, Methood Overloading is not possible by changing the return type of the method.
In this example, we have created two overloaded methods, first sum method performs addition of two
numbers and second sum method performs addition of three numbers.
1. class Calculation{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. Calculation obj=new Calculation();
7. obj.sum(10,10,10);
8. obj.sum(20,20);
9.
10. }
11. }
Test it Now
Output:30
40
In this example, we have created two overloaded methods that differs in data type. The first sum method
receives two integer arguments and second sum method receives two double arguments.
1. class Calculation2{
2. void sum(int a,int b){System.out.println(a+b);}
3. void sum(double a,double b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation2 obj=new Calculation2();
7. obj.sum(10.5,10.5);
8. obj.sum(20,20);
9.
10. }
11. }
Test it Now
Output:21.0
40
Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because there may
occur ambiguity. Let's see how ambiguity may occur:
1. class Calculation3{
2. int sum(int a,int b){System.out.println(a+b);}
3. double sum(int a,int b){System.out.println(a+b);}
4.
5. public static void main(String args[]){
6. Calculation3 obj=new Calculation3();
7. int result=obj.sum(20,20); //Compile Time Error
8.
9. }
10. }
Test it Now
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
Can we overload main() method?
Yes, by method overloading. You can have any number of main methods in a class by method overloading.
Let's see the simple example:
1. class Overloading1{
2. public static void main(int a){
3. System.out.println(a);
4. }
5.
6. public static void main(String args[]){
7. System.out.println("main() method invoked");
8. main(10);
9. }
10. }
Test it Now
Output:main() method invoked
10
One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept by
the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short
datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float or
double and so on.
If there are matching type arguments in the method, type promotion is not performed.
1. class OverloadingCalculation2{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }
Test it Now
Output:int arg method invoked
If there are no matching type arguments in the method, and each method promotes similar number of
arguments, there will be ambiguity.
1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }
Test it Now
Output:Compile Time Error
Constructor in Java
1. Types of constructors
1. Default Constructor
2. Parameterized Constructor
2. Constructor Overloading
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for
the object that is why it is known as constructor.
2. Parameterized constructor
Java Default Constructor
1. <class_name>(){}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of
object creation.
1. class Bike1{
2. Bike1(){System.out.println("Bike is created");}
3. public static void main(String args[]){
4. Bike1 b=new Bike1();
5. }
6. }
Test it Now
Output:
Bike is created
Default constructor provides the default values to the object like 0, null etc. depending on the type.
Test it Now
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor.Here 0 and null values are provided by default constructor.
In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.
1. class Student4{
2. int id;
3. String name;
4.
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student4 s1 = new Student4(111,"Karan");
13. Student4 s2 = new Student4(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }
Test it Now
Output:
111 Karan
222 Aryan
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists.The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.
Test it Now
Output:
111 Karan 0
222 Aryan 25
Constructor is used to initialize the state of an object. Method is used to expose behaviour of an
object.
Constructor must not have return type. Method must have return type.
The java compiler provides a default constructor if you don't have Method is not provided by compiler in any
any constructor. case.
Constructor name must be same as the class name. Method name may or may not be same as
class name.
By constructor
In this example, we are going to copy the values of one object into another using java constructor.
1. class Student6{
2. int id;
3. String name;
4. Student6(int i,String n){
5. id = i;
6. name = n;
7. }
8.
9. Student6(Student6 s){
10. id = s.id;
11. name =s.name;
12. }
13. void display(){System.out.println(id+" "+name);}
14.
15. public static void main(String args[]){
16. Student6 s1 = new Student6(111,"Karan");
17. Student6 s2 = new Student6(s1);
18. s1.display();
19. s2.display();
20. }
21. }
Test it Now
Output:
111 Karan
111 Karan
1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }
Test it Now
Output:
111 Karan
111 Karan
Ans:yes, that is current class instance (You cannot use return type yet it returns a value).
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the
constructor as you perform in the method.
Inheritance in Java
1. Inheritance
2. Types of Inheritance
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent
object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add
new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
The extends keyword indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship
between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e.
code reusability.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
Note: Multiple inheritance is not supported in java through class.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
Q) Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B
classes have same method and you call it from child class object, there will be ambiguity to call method of A
or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2
classes. So whether you have same method or different, there will be compile time error now.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Test it Now
Compile Time Error
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains
one more object named address, which contains its own informations such as city, state, country, zipcode
etc. as given below.
1. class Employee{
2. int id;
3. String name;
4. Address address;//Address is a class
5. ...
6. }
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.
In this example, we have created the reference of Operation class in the Circle class.
1. class Operation{
2. int square(int n){
3. return n*n;
4. }
5. }
6.
7. class Circle{
8. Operation op;//aggregation
9. double pi=3.14;
10.
11. double area(int radius){
12. op=new Operation();
13. int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
14. return pi*rsquare;
15. }
16.
17.
18.
19. public static void main(String args[]){
20. Circle c=new Circle();
21. double result=c.area(5);
22. System.out.println(result);
23. }
24. }
Test it Now
Output:78.5
Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the
objects involved; otherwise, aggregation is the best choice.
In this example, Employee has an object of Address, address object contains its own informations such as
city, state, country etc. In such case relationship is Employee HAS-A address.
Address.java
Emp.java
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.
In other words, If subclass provides the specific implementation of the method that has been provided by
one of its parent class, it is known as method overriding.
Let's understand the problem that we may face in the program if we don't use method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike extends Vehicle{
5.
6. public static void main(String args[]){
7. Bike obj = new Bike();
8. obj.run();
9. }
10. }
Test it Now
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is why we use
method overriding.
In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method is same and there is IS-A
relationship between the classes, so there is method overriding.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. }
4. class Bike2 extends Vehicle{
5. void run(){System.out.println("Bike is running safely");}
6.
7. public static void main(String args[]){
8. Bike2 obj = new Bike2();
9. obj.run();
10. }
Test it Now
Output:Bike is running safely
No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.
Why we cannot override static method?
because static method is bound with class whereas instance method is bound with object. Static belongs to
class area and instance belongs to heap area.
Before Java5, it was not possible to override any method by changing the return type. But now, since Java5,
it is possible to override method by changing the return type if subclass overrides any method whose return
type is Non-Primitive but it changes its return type to subclass type. Let's take a simple example:
Note: If you are beginner to java, skip this topic and return to it after OOPs concepts.
As you can see in the above example, the return type of the get() method of A class is A but the return type
of the get() method of B class is B. Both methods have different return type but it is method overriding. This
is known as covariant return type.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred
by super reference variable.
In the above example Vehicle and Bike both class have a common property speed. Instance variable of
current class is refered by instance bydefault, but I have to refer parent class instance variable that is
why we use super keyword to distinguish between parent class instance variable and current class
instance variable.
The super keyword can also be used to invoke the parent class constructor as given below:
1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}
3. }
4.
5. class Bike5 extends Vehicle{
6. Bike5(){
7. super();//will invoke parent class constructor
8. System.out.println("Bike is created");
9. }
10. public static void main(String args[]){
11. Bike5 b=new Bike5();
12.
13. }
14. }
Test it Now
Output:Vehicle is created
Bike is created
As we know well that default constructor is provided by compiler automatically but it also adds super() for
the first statement.If you are creating your own constructor and you don't have either this() or super() as
the first statement, compiler will provide super() as the first statement of the constructor.
1. class Vehicle{
2. Vehicle(){System.out.println("Vehicle is created");}
3. }
4.
5. class Bike6 extends Vehicle{
6. int speed;
7. Bike6(int speed){
8. this.speed=speed;
9. System.out.println(speed);
10. }
11. public static void main(String args[]){
12. Bike6 b=new Bike6(10);
13. }
14. }
Test it Now
Output:Vehicle is created
10
The super keyword can also be used to invoke parent class method. It should be used in case subclass
contains the same method as parent class as in the example given below:
1. class Person{
2. void message(){System.out.println("welcome");}
3. }
4.
5. class Student16 extends Person{
6. void message(){System.out.println("welcome to java");}
7.
8. void display(){
9. message();//will invoke current class message() method
10. super.message();//will invoke parent class message() method
11. }
12.
13. public static void main(String args[]){
14. Student16 s=new Student16();
15. s.display();
16. }
17. }
Test it Now
Output:welcome to java
welcome
In the above example Student and Person both classes have message() method if we call message()
method from Student class, it will call the message() method of Student class not of Person class
because priority is given to local.
In case there is no method in subclass as parent, there is no need to use super. In the example given
below message() method is invoked from Student class but Student class does not have message()
method, so you can directly call message() method.
1. class Person{
2. void message(){System.out.println("welcome");}
3. }
4.
5. class Student17 extends Person{
6.
7. void display(){
8. message();//will invoke parent class message() method
9. }
10.
11. public static void main(String args[]){
12. Student17 s=new Student17();
13. s.display();
14. }
15. }
Test it Now
Output:welcome
Instance initializer block:
1. Instance initializer block
Instance Initializer block is used to initialize the instance data member. It run each time when object
of the class is created.
The initialization of the instance variable can be directly but there can be performed extra operations
while initializing the instance variable in the instance initializer block.
Que) What is the use of instance initializer block while we can directly assign a value
in instance data member? For example:
1. class Bike{
2. int speed=100;
3. }
Suppose I have to perform some operations while assigning value to instance data member e.g. a for
loop to fill a complex array or error handling etc.
Let's see the simple example of instance initializer block the performs initialization.
1. class Bike7{
2. int speed;
3.
4. Bike7(){System.out.println("speed is "+speed);}
5.
6. {speed=100;}
7.
8. public static void main(String args[]){
9. Bike7 b1=new Bike7();
10. Bike7 b2=new Bike7();
11. }
12. }
Test it Now
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
1. method
2. constructor
3. block
In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer
block is invoked at the time of object creation. The java compiler copies the instance initializer block in
the constructor after the first statement super(). So firstly, constructor is invoked. Let's understand it by
the figure given below:
Note: The java compiler copies the code of instance initializer block in every
constructor.
Rules for instance initializer block :
There are mainly three rules for the instance initializer block. They are as follows:
1. The instance initializer block is created when instance of the class is created.
2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after
super() constructor call).
3. The instance initializer block comes in the order in which they appear.
2. Final method
3. Final class
7. Final parameter
The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final
variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can
be static also which will be initialized in the static block only. We will have detailed learning of these. Let's
first learn the basics of final keyword.
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed
because final variable once assigned a value can never be changed.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Test it Now
Output:Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
Ans) Yes, final method is inherited but you cannot override it. For Example:
1. class Bike{
2. final void run(){System.out.println("running...");}
3. }
4. class Honda2 extends Bike{
5. public static void main(String args[]){
6. new Honda2().run();
7. }
8. }
Test it Now
Output:running...
A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once initialized may not
be changed, it is useful. For example PAN CARD number of an employee.
1. class Bike10{
2. final int speedlimit;//blank final variable
3.
4. Bike10(){
5. speedlimit=70;
6. System.out.println(speedlimit);
7. }
8.
9. public static void main(String args[]){
10. new Bike10();
11. }
12. }
Test it Now
Output:70
static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It
can be initialized only in static block.
If you declare any parameter as final, you cannot change the value of it.
1. class Bike11{
2. int cube(final int n){
3. n=n+2;//can't be changed as n is final
4. n*n*n;
5. }
6. public static void main(String args[]){
7. Bike11 b=new Bike11();
8. b.cube(5);
9. }
10. }
Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs"
means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We
can perform polymorphism in java by method overloading and method overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on
runtime polymorphism in java.
Runtime Polymorphism in Java
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden
method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference variable.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as upcasting. For
example:
1. class A{}
2. class B extends A{}
1. A a=new B();//upcasting
In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike class and
overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it
refers to the subclass object and subclass method overrides the Parent class method, subclass method is
invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splender extends Bike{
5. void run(){System.out.println("running safely with 60km");}
6.
7. public static void main(String args[]){
8. Bike b = new Splender();//upcasting
9. b.run();
10. }
11. }
Test it Now
Output:running safely with 60km.
1. class Bank{
2. int getRateOfInterest(){return 0;}
3. }
4.
5. class SBI extends Bank{
6. int getRateOfInterest(){return 8;}
7. }
8.
9. class ICICI extends Bank{
10. int getRateOfInterest(){return 7;}
11. }
12. class AXIS extends Bank{
13. int getRateOfInterest(){return 9;}
14. }
15.
16. class Test3{
17. public static void main(String args[]){
18. Bank b1=new SBI();
19. Bank b2=new ICICI();
20. Bank b3=new AXIS();
21. System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
22. System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
23. System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
24. }
25. }
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data
members.
In the example given below, both the classes have a datamember speedlimit, we are accessing the
datamember by the reference variable of Parent class which refers to the subclass object. Since we are
accessing the datamember which is not overridden, hence it will access the datamember of Parent class
always.
1. class Bike{
2. int speedlimit=90;
3. }
4. class Honda3 extends Bike{
5. int speedlimit=150;
6.
7. public static void main(String args[]){
8. Bike obj=new Honda3();
9. System.out.println(obj.speedlimit);//90
10. }
Test it Now
Output:90
1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4.
5. class Dog extends Animal{
6. void eat(){System.out.println("eating fruits");}
7. }
8.
9. class BabyDog extends Dog{
10. void eat(){System.out.println("drinking milk");}
11.
12. public static void main(String args[]){
13. Animal a1,a2,a3;
14. a1=new Animal();
15. a2=new Dog();
16. a3=new BabyDog();
17.
18. a1.eat();
19. a2.eat();
20. a3.eat();
21. }
22. }
Test it Now
Output: eating
eating fruits
drinking Milk
Understanding Type
Let's understand the type of instance.
1. int data=30;
1. class Dog{
2. public static void main(String args[]){
3. Dog d1;//Here d1 is a type of Dog
4. }
5. }
static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
If there is any private, final or static method in a class, there is static binding.
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
In the above example object type cannot be determined by the compiler, because the instance of Dog is
also an instance of Animal.So compiler doesn't know its type, only its base type.
Java instanceof
1. java instanceof
3. Applying the instanceof operator with a variable the have null value
The instanceof in java is also known as type comparison operatorbecause it compares the instance with
type. It returns either true or false. If we apply the instanceof operator with any variable that has null value,
it returns false.
Let's see the simple example of instance operator where it tests the current class.
1. class Simple1{
2. public static void main(String args[]){
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple);//true
5. }
6. }
Test it Now
Output:true
An object of subclass type is also a type of parent class. For example, if Dog extends Animal then object of
Dog can be referred by either Dog or Animal class.
1. class Dog2{
2. public static void main(String args[]){
3. Dog2 d=null;
4. System.out.println(d instanceof Dog2);//false
5. }
6. }
Test it Now
Output:false
1. class Animal { }
2.
3. class Dog3 extends Animal {
4. static void method(Animal a) {
5. if(a instanceof Dog3){
6. Dog3 d=(Dog3)a;//downcasting
7. System.out.println("ok downcasting performed");
8. }
9. }
10.
11. public static void main (String [] args) {
12. Animal a=new Dog3();
13. Dog3.method(a);
14. }
15.
16. }
Test it Now
Output:ok downcasting performed
Downcasting can also be performed without the use of instanceof operator as displayed in the following
example:
1. class Animal { }
2. class Dog4 extends Animal {
3. static void method(Animal a) {
4. Dog4 d=(Dog4)a;//downcasting
5. System.out.println("ok downcasting performed");
6. }
7. public static void main (String [] args) {
8. Animal a=new Dog4();
9. Dog4.method(a);
10. }
11. }
Test it Now
Output:ok downcasting performed
Let's take closer look at this, actual object that is referred by a, is an object of Dog class. So if we downcast
it, it is fine. But what will happen if we write:
1. interface Printable{}
2. class A implements Printable{
3. public void a(){System.out.println("a method");}
4. }
5. class B implements Printable{
6. public void b(){System.out.println("b method");}
7. }
8.
9. class Call{
10. void invoke(Printable p){//upcasting
11. if(p instanceof A){
12. A a=(A)p;//Downcasting
13. a.a();
14. }
15. if(p instanceof B){
16. B b=(B)p;//Downcasting
17. b.b();
18. }
19.
20. }
21. }//end of Call class
22.
23. class Test4{
24. public static void main(String args[]){
25. Printable p=new B();
26. Call c=new Call();
27. c.invoke(p);
28. }
29. }
Test it Now
Output: b method
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and
non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example sending
sms, you just type the text and send the message. You don't know the internal processing about the
message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
2. Interface (100%)
abstract method
A method that is declared as abstract and does not have implementation is known as abstract method.
A factory method is the method that returns the instance of the class. We will learn about the factory
method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked.
File: TestAbstraction1.java
File: TestAbstraction2.java
Rule: If there is any abstract method in a class, that class must be abstract.
1. class Bike12{
2. abstract void run();
3. }
Test it Now
compile time error
Rule: If you are extending any abstract class that have abstract method, you must either provide the
implementation of the method or make this class abstract.
Note: If you are beginner to java, learn interface first and skip this example.
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am C");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}
14. public void b(){System.out.println("I am b");}
15. public void d(){System.out.println("I am d");}
16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}
Test it Now
Output:I am a
I am b
I am c
I am d
Interface in Java
1. Interface
2. Example of Interface
3. Multiple inheritance by Interface
4. Why multiple inheritance is supported in Interface while it is not supported in case of class.
5. Marker Interface
6. Nested Interface
An interface in java is a blueprint of a class. It has static constants and abstract methods only.
The interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods in
the java interface not method body. It is used to achieve fully abstraction and multiple inheritance in Java.
The java compiler adds public and abstract keywords before the interface method and public, static and final
keywords before data members.
In other words, Interface fields are public, static and final bydefault, and methods are public and abstract.
Understanding relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface but
a class implements an interface.
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the A class.
1. interface printable{
2. void print();
3. }
4.
5. class A6 implements printable{
6. public void print(){System.out.println("Hello");}
7.
8. public static void main(String args[]){
9. A6 obj = new A6();
10. obj.print();
11. }
12. }
Test it Now
Output:Hello
As we have explained in the inheritance chapter, multiple inheritance is not supported in case of class.
But it is supported in case of interface because there is no ambiguity as implementation is provided by
the implementation class. For example:
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestTnterface1 implements Printable,Showable{
9. public void print(){System.out.println("Hello");}
10. public static void main(String args[]){
11. TestTnterface1 obj = new TestTnterface1();
12. obj.print();
13. }
14. }
Test it Now
Hello
As you can see in the above example, Printable and Showable interface have same methods but its
implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
A class implements interface but one interface extends another interface .
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class Testinterface2 implements Showable{
8.
9. public void print(){System.out.println("Hello");}
10. public void show(){System.out.println("Welcome");}
11.
12. public static void main(String args[]){
13. Testinterface2 obj = new Testinterface2();
14. obj.print();
15. obj.show();
16. }
17. }
Test it Now
Hello
Welcome
1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstractmethods.
3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.
4) Abstract class can have static methods, main Interface can't have static methods, main
method and constructor. method or constructor.
5) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.
6) The abstract keyword is used to declare abstract The interface keyword is used to declare interface.
class.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction
(100%).
Output:
I am a
I am b
I am c
I am d
Q1 whats the difference between a class variable and an instance variable?
//save A.java
package p1;
public class A{
Compile
Javac d . A.java
//save B.java
package p2;
public class B{
Compile
Javac d . B.java
//save C.java
package p3;
public class C{
Compile
Javac d . C.java
// save D.java
package p4;
import p1.*;
import p2.*;
import p3.*;
class D
{
A ob = new A();
ob.m_1();
obj.m_2();
C o = new C();
o.m_3();
Compile
Javac d . D.java
Run
Java p4.C