There is no copy constructor in java. But, we can copy the values of one object to another
like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
Q) Does constructor return any value?
Ans:yes, that is current class instance (You cannot use return type yet it returns a value.
This is an implicit event. If you do not create constructor, the program will create default
constructor internally.).
class demo
{
demo{}
}
class demo1
{
public static void main(String as[])
{
demo d = new demo();
System.out.println(d);
}
}
output: demo@7d4991ad it is the reference id of the object 'd' of class demo which is returned
by the constructor. if u will not define your constructor then jvm will get this id from default
constructor.
you can cross check it by this line: System.out.println(new demo()); output: demo@1b6d3586.
since every object has its separate heap area in memory so reference id of each object also
vary.
Can constructor perform other tasks instead of initialization?
Yes, like object creation, starting a thread, calling method etc. You can perform any operation
in the constructor as you perform in the method.
Java static keyword
The
static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class. The static keyword belongs
to the class rather than instance of the class.
The static can be:
- variable (also known as class variable)
- method (also known as class method)
- block
- nested class
1) Java static variable
If you declare any variable as static, it is known static variable.
- The static variable can be used to refer the common property of all objects (that
is not unique for each object) e.g. company name of employees,college name of students etc.
- The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program
memory efficient (i.e it saves memory).
Understanding problem without static variable
- class Student{
- int rollno;
- String name;
- String college="ITS";
- }
Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once.
Java static property is shared to all objects.
Example of static variable
-
-
- class Student8{
- int rollno;
- String name;
- static String college ="ITS";
-
- Student8(int r,String n){
- rollno = r;
- name = n;
- }
- void display (){System.out.println(rollno+" "+name+" "+college);}
-
- public static void main(String args[]){
- Student8 s1 = new Student8(111,"Karan");
- Student8 s2 = new Student8(222,"Aryan");
-
- s1.display();
- s2.display();
- }
- }
Output:111 Karan ITS
222 Aryan ITS

Program of counter without static variable
In this example, we have created an instance variable named count which is incremented in
the constructor. Since instance variable gets the memory at the time of object creation, each
object will have the copy of the instance variable, if it is incremented, it won't reflect to
other objects. So each objects will have the value 1 in the count variable.
- class Counter{
- int count=0;
-
- Counter(){
- count++;
- System.out.println(count);
- }
-
- public static void main(String args[]){
-
- Counter c1=new Counter();
- Counter c2=new Counter();
- Counter c3=new Counter();
-
- }
- }
Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value. |
- class Counter2{
- static int count=0;
-
- Counter2(){
- count++;
- System.out.println(count);
- }
-
- public static void main(String args[]){
-
- Counter2 c1=new Counter2();
- Counter2 c2=new Counter2();
- Counter2 c3=new Counter2();
-
- }
- }
2) Java static method
If you apply static keyword with any method, it is known as static method.
- A static method belongs to the class rather than object of a class.
- A static method can be invoked without the need for creating an instance of a class.
- static method can access static data member and can change the value of it.
Example of static method
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Another example of static method that performs normal calculation
//Program to get cube of a given number by static method
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
Restrictions for static method
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
this and super cannot be used in static context.
class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
Output:Compile Time Error
Q) why java main method is static?
Ans) because object is not required to call static method if it were non-static method, jvm
create object first then call main() method that will lead the problem of extra memory
allocation.
3) Java static block
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
Example of static block
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output:static block is invoked
Hello main
Q) Can we execute a program without main() method?
No from JDK 1.7
Before it was possible using Static block.
this keyword in java
There can be a lot of usage of
java this keyword. In java, this is a
reference variable that
refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
- this can be used to refer current class instance variable.
- this can be used to invoke current class method (implicitly)
- this() can be used to invoke current class constructor.
- this can be passed as an argument in the method call.
- this can be passed as argument in the constructor call.
- this can be used to return the current class instance from the method.
1) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity.
If local variables(formal arguments) and instance variables are different, there is no need to use this keyword.
It is better approach to use meaningful names for variables. So we use same name for instance
variables and parameters in real time, and always use this keyword.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Rule: Call to this() must be the first statement in constructor.
class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this.fee=fee;
this(rollno,name,course);
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestThis8{
public static void main(String args[]){
Student s1=new Student(111,"ankit","java");
Student s2=new Student(112,"sumit","java",6000f);
s1.display();
s2.display();
}}
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.
Q) Why Method Overloading is not possible by changing the return
type of method only?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:
- class Adder{
- static int add(int a,int b){return a+b;}
- static double add(int a,int b){return a+b;}
- }
- class TestOverloading3{
- public static void main(String[] args){
- System.out.println(Adder.add(11,11));
- }}
Compile Time Error: method add(int,int) is already defined in class Adder
Note: Compile Time Error is better than Run Time Error. So, java compiler renders
compiler time error if you declare the same method having same parameters.
Can we overload java main() method?
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only.
Let's see the simple example:
- class TestOverloading4{
- public static void main(String[] args){System.out.println("main with String[]");}
- public static void main(String args){System.out.println("main with String");}
- public static void main(){System.out.println("main without args");}
- }
Output:
Method Overloading and Type Promotion
class OverloadingCalculation1{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);
obj.sum(20,20,20);
}
}
class OverloadingCalculation1{
void sum(int a, int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,'a');
obj.sum(20,20,20);
}
}
Output: 117
Method Overriding in 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.
Usage of Java Method Overriding
- Method overriding is used to provide specific implementation of a method that is
already provided by its super class.
- Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
- method must have same name as in the parent class
- method must have same parameter as in the parent class.
- must be IS-A relationship (inheritance).
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
}
Can we override static method?
No, static method cannot be overridden.
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.
Can we override java main method?
No, because main is a static method.
Difference between method overloading and method overriding in java
There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below:
No. | Method Overloading | Method Overriding |
1) | Method overloading is used to increase the readability of the program. | Method overriding is used to provide the specific implementation of the method that is already provided by its super class. |
2) | Method overloading is performed within class. | Method overriding occurs in two classes that have IS-A (inheritance) relationship. |
3) | In case of method overloading, parameter must be different. | In case of method overriding, parameter must be same. |
4) | Method overloading is the example of compile time polymorphism. | Method overriding is the example of run time polymorphism. |
5) | In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. | Return type must be same or covariant in method overriding. |
super keyword in java
The super keyword in java is a reference variable which is used to refer immediate parent
class object. Whenever you create the instance of subclass, an instance of parent class
is created implicitly which is referred by super reference variable.
Usage of java super Keyword
- super can be used to refer immediate parent class instance variable.
- super can be used to invoke immediate parent class method.
- super() can be used to invoke immediate parent class constructor.
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields.
- class Animal{
- String color="white";
- }
- class Dog extends Animal{
- String color="black";
- void printColor(){
- System.out.println(color);
- System.out.println(super.color);
- }
- }
- class TestSuper1{
- public static void main(String args[]){
- Dog d=new Dog();
- d.printColor();
- }}
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.
- class Animal{
- void eat(){System.out.println("eating...");}
- }
- class Dog extends Animal{
- void eat(){System.out.println("eating bread...");}
- void bark(){System.out.println("barking...");}
- void work(){
- super.eat();
- bark();
- }
- }
- class TestSuper2{
- public static void main(String args[]){
- Dog d=new Dog();
- d.work();
- }}
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor. Let's see a simple example:
- class Animal{
- Animal(){System.out.println("animal is created");}
- }
- class Dog extends Animal{
- Dog(){
- super();
- System.out.println("dog is created");
- }
- }
- class TestSuper3{
- public static void main(String args[]){
- Dog d=new Dog();
- }}
Note: super() is added in each class constructor automatically by compiler if there is no super() or this().

As we know well that default constructor is provided by compiler automatically if there
is no constructor. But, it also adds super() as the first statement.
Another example of super keyword where super() is provided by the compiler
implicitly.
- class Animal{
- Animal(){System.out.println("animal is created");}
- }
- class Dog extends Animal{
- Dog(){
- System.out.println("dog is created");
- }
- }
- class TestSuper4{
- public static void main(String args[]){
- Dog d=new Dog();
- }}
super example: real use
Let's see the real use of super keyword. Here, Emp class inherits Person class so all the properties of Person will be inherited to Emp by default. To initialize all the property, we are using parent class constructor from child class. In such way, we are reusing the parent class constructor.
- class Person{
- int id;
- String name;
- Person(int id,String name){
- this.id=id;
- this.name=name;
- }
- }
- class Emp extends Person{
- float salary;
- Emp(int id,String name,float salary){
- super(id,name);
- this.salary=salary;
- }
- void display(){System.out.println(id+" "+name+" "+salary);}
- }
- class TestSuper5{
- public static void main(String[] args){
- Emp e1=new Emp(1,"ankit",45000f);
- e1.display();
- }}
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.
Example of instance initializer block
Let's see the simple example of instance initializer block the performs initialization. |
- class Bike7{
- int speed;
-
- Bike7(){System.out.println("speed is "+speed);}
-
- {speed=100;}
-
- public static void main(String args[]){
- Bike7 b1=new Bike7();
- Bike7 b2=new Bike7();
- }
- }
|
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
- method
- constructor
- block
|
What is invoked first, instance initializer block or constructor?
- class Bike8{
- int speed;
-
- Bike8(){System.out.println("constructor is invoked");}
-
- {System.out.println("instance initializer block invoked");}
-
- public static void main(String args[]){
- Bike8 b1=new Bike8();
- Bike8 b2=new Bike8();
- }
- }
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
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: |
- The instance initializer block is created when instance of the class is created.
- The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
- The instance initializer block comes in the order in which they appear.
Program of instance initializer block that is invoked after super()
- class A{
- A(){
- System.out.println("parent class constructor invoked");
- }
- }
- class B2 extends A{
- B2(){
- super();
- System.out.println("child class constructor invoked");
- }
-
- {System.out.println("instance initializer block is invoked");}
-
- public static void main(String args[]){
- B2 b=new B2();
- }
- }
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
Another example of instance block
- class A{
- A(){
- System.out.println("parent class constructor invoked");
- }
- }
-
- class B3 extends A{
- B3(){
- super();
- System.out.println("child class constructor invoked");
- }
-
- B3(int a){
- super();
- System.out.println("child class constructor invoked "+a);
- }
-
- {System.out.println("instance initializer block is invoked");}
-
- public static void main(String args[]){
- B3 b1=new B3();
- B3 b2=new B3(10);
- }
- }
Output:parent class constructor invoked
instance initializer block is invoked
child class constructor invoked
parent class constructor invoked
instance initializer block is invoked
child class constructor invoked 10
We can put code in a constructor or a method or an initialization block. What is the
use of initialization block? Is it necessary that every java program must have it?
- instance initialization blocks, and
- static initialization blocks.
This code should illustrate the use of them and in which order they are executed:
public class Test {
static int staticVariable;
int nonStaticVariable;
// Static initialization block:
// Runs once (when the class is initialized)
static {
System.out.println("Static initalization.");
staticVariable = 5;
}
// Instance initialization block:
// Runs each time you instantiate an object
{
System.out.println("Instance initialization.");
nonStaticVariable = 7;
}
public Test() {
System.out.println("Constructor.");
}
public static void main(String[] args) {
new Test();
new Test();
}
}
Prints:
Static initalization.
Instance initialization.
Constructor.
Instance initialization.
Constructor.
Instance itialization blocks are useful if you want to have some code run regardless of which
constructor is used or if you want to do some instance initialization for anonymous classes.
Order of execution:
static initialization blocks of super classes
static initialization blocks of the class
instance initialization blocks of super classes
constructors of super classes
instance initialization blocks of the class
constructor of the class.
A couple of additional points to keep in mind :
The code in static initialization block will be executed at class load time (and yes, that means only once per class load), before any instances of the class are constructed and before any static methods are called.
The instance initialization block is actually copied by the Java compiler into every constructor the class has. So every time the code in instance initialization block is executed exactly before the code in constructor.
public class StaticTest extends parent {
static {
System.out.println("inside satic block");
}
StaticTest() {
System.out.println("inside constructor of child");
}
{
System.out.println("inside initialization block");
}
public static void main(String[] args) {
new StaticTest();
new StaticTest();
System.out.println("inside main");
}
}
class parent {
static {
System.out.println("inside parent Static block");
}
{
System.out.println("inside parent initialisation block");
}
parent() {
System.out.println("inside parent constructor");
}
}
this gives
inside parent Static block
inside satic block
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside main
its like stating the obvious but seems a little more clear.
import java.io.*;
public class GFG
{
{
System.out.println( "Common part of constructors invoked !!" );
}
public GFG()
{
System.out.println( "Default Constructor invoked" );
}
public GFG( int x)
{
System.out.println( "Parametrized constructor invoked" );
}
public static void main(String arr[])
{
GFG obj1, obj2;
obj1 = new GFG();
obj2 = new GFG( 0 );
}
}
|
Output:
Common part of constructors invoked!!
Default Constructor invoked
Common part of constructors invoked!!
Parametrized constructor invoked
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:
- variable
- method
- 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.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable
(It will be constant).
Example of final variable
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
class Bike9{
final int speedlimit=90;
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}
Output:Compile Time Error
2) Java final method
If you make any method as final, you cannot override it.
Example of final method
- class Bike{
- final void run(){System.out.println("running");}
- }
-
- class Honda extends Bike{
- void run(){System.out.println("running safely with 100kmph");}
-
- public static void main(String args[]){
- Honda honda= new Honda();
- honda.run();
- }
- }
Output:Compile Time Error
3) Java final class
If you make any class as final, you cannot extend it.
Example of final class
- final class Bike{}
-
- class Honda1 extends Bike{
- void run(){System.out.println("running safely with 100kmph");}
-
- public static void main(String args[]){
- Honda1 honda= new Honda1();
- honda.run();
- }
- }
Output:Compile Time Error
Q) Is final method inherited?
Ans) Yes, final method is inherited but you cannot override it. For Example:
- class Bike{
- final void run(){System.out.println("running...");}
- }
- class Honda2 extends Bike{
- public static void main(String args[]){
- new Honda2().run();
- }
- }
Output:running...
Q) What is blank or uninitialized final variable?
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.
It can be initialized only in constructor.
Que) Can we initialize blank final variable?
Yes, but only in constructor. For example:
- class Bike10{
- final int speedlimit;
-
- Bike10(){
- speedlimit=70;
- System.out.println(speedlimit);
- }
-
- public static void main(String args[]){
- new Bike10();
- }
- }
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.
Example of static blank final variable
- class A{
- static final int data;
- static{ data=50;}
- public static void main(String args[]){
- System.out.println(A.data);
- }
- }
Q) What is final parameter?
If you declare any parameter as final, you cannot change the value of it.
- class Bike11{
- int cube(final int n){
- n=n+2;
- n*n*n;
- }
- public static void main(String args[]){
- Bike11 b=new Bike11();
- b.cube(5);
- }
- }
Output: Compile Time Error
Q) Can we declare a constructor final?
No, because constructor is never inherited.
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.Let's first understand the upcasting before Runtime
Polymorphism.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
- class A{}
- class B extends A{}
Example of Java Runtime Polymorphism
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.
- class Bike{
- void run(){System.out.println("running");}
- }
- class Splender extends Bike{
- void run(){System.out.println("running safely with 60km");}
-
- public static void main(String args[]){
- Bike b = new Splender();
- b.run();
- }
- }
Output:running safely with 60km.
Java Runtime Polymorphism Example: Bank
Consider a scenario, Bank is a class that provides method to get the rate of interest. But, rate of interest may differ according to banks. For example, SBI, ICICI and AXIS banks are providing 8.4%, 7.3% and 9.7% rate of interest.

- class Bank{
- float getRateOfInterest(){return 0;}
- }
- class SBI extends Bank{
- float getRateOfInterest(){return 8.4f;}
- }
- class ICICI extends Bank{
- float getRateOfInterest(){return 7.3f;}
- }
- class AXIS extends Bank{
- float getRateOfInterest(){return 9.7f;}
- }
- class TestPolymorphism{
- public static void main(String args[]){
- Bank b;
- b=new SBI();
- System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
- b=new ICICI();
- System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
- b=new AXIS();
- System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
- }
- }
Output:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
Java Runtime Polymorphism Example: Shape
- class Shape{
- void draw(){System.out.println("drawing...");}
- }
- class Rectangle extends Shape{
- void draw(){System.out.println("drawing rectangle...");}
- }
- class Circle extends Shape{
- void draw(){System.out.println("drawing circle...");}
- }
- class Triangle extends Shape{
- void draw(){System.out.println("drawing triangle...");}
- }
- class TestPolymorphism2{
- public static void main(String args[]){
- Shape s;
- s=new Rectangle();
- s.draw();
- s=new Circle();
- s.draw();
- s=new Triangle();
- s.draw();
- }
- }
Output:
drawing rectangle...
drawing circle...
drawing triangle...
Java Runtime Polymorphism Example: Animal
- class Animal{
- void eat(){System.out.println("eating...");}
- }
- class Dog extends Animal{
- void eat(){System.out.println("eating bread...");}
- }
- class Cat extends Animal{
- void eat(){System.out.println("eating rat...");}
- }
- class Lion extends Animal{
- void eat(){System.out.println("eating meat...");}
- }
- class TestPolymorphism3{
- public static void main(String[] args){
- Animal a;
- a=new Dog();
- a.eat();
- a=new Cat();
- a.eat();
- a=new Lion();
- a.eat();
- }}
Output:
eating bread...
eating rat...
eating meat...
Java Runtime Polymorphism with Data Member
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. |
Rule: Runtime polymorphism can't be achieved by data members.
- class Bike{
- int speedlimit=90;
- }
- class Honda3 extends Bike{
- int speedlimit=150;
-
- public static void main(String args[]){
- Bike obj=new Honda3();
- System.out.println(obj.speedlimit);
- }
Output:
Java Runtime Polymorphism with Multilevel Inheritance
Let's see the simple example of Runtime Polymorphism with multilevel inheritance.
- class Animal{
- void eat(){System.out.println("eating");}
- }
- class Dog extends Animal{
- void eat(){System.out.println("eating fruits");}
- }
- class BabyDog extends Dog{
- void eat(){System.out.println("drinking milk");}
- public static void main(String args[]){
- Animal a1,a2,a3;
- a1=new Animal();
- a2=new Dog();
- a3=new BabyDog();
- a1.eat();
- a2.eat();
- a3.eat();
- }
- }
Output:
eating
eating fruits
drinking Milk
Try for Output
- class Animal{
- void eat(){System.out.println("animal is eating...");}
- }
- class Dog extends Animal{
- void eat(){System.out.println("dog is eating...");}
- }
- class BabyDog1 extends Dog{
- public static void main(String args[]){
- Animal a=new BabyDog1();
- a.eat();
- }}
Output:
Since, BabyDog is not overriding the eat() method, so eat() method of Dog class is invoked.
Static Binding and Dynamic Binding
Connecting a method call to the method body is known as binding.
There are two types of binding
- static binding (also known as early binding).
- dynamic binding (also known as late binding).
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.
Example of static binding
- class Dog{
- private void eat(){System.out.println("dog is eating...");}
-
- public static void main(String args[]){
- Dog d1=new Dog();
- d1.eat();
- }
- }
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
- class Animal{
- void eat(){System.out.println("animal is eating...");}
- }
-
- class Dog extends Animal{
- void eat(){System.out.println("dog is eating...");}
-
- public static void main(String args[]){
- Animal a=new Dog();
- a.eat();
- }
- }
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.
Here are few important difference between static and dynamic binding
1) Static binding in Java occurs during Compile time while Dynamic binding occurs during Runtime.
2) private, final and static methods and variables uses static binding and bonded by compiler while virtual methods are bonded during runtime based upon runtime object.
3) Static binding uses Type(Class in Java) information for binding while Dynamic binding uses Object to resolve binding.
3) Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
Here is an example which will help you to understand both static and dynamic binding in Java.
Static Binding Example in Java
public class StaticBindingTest
{
public static void main(String args[])
{
Collection c = new HashSet();
StaticBindingTest et = new StaticBindingTest();
et.sort(c);
}
//overloaded method takes Collection argument
public Collection sort(Collection c)
{
System.out.println("Inside Collection sort method");
return c;
}
//another overloaded method which takes HashSet argument which is sub class
public Collection sort(HashSet hs)
{
System.out.println("Inside HashSet sort method");
return hs;
}
}
Output: Inside Collection sort method
Example of Dynamic Binding in Java
public class DynamicBindingTest
{
public static void main(String args[])
{
Vehicle vehicle = new Car(); //here Type is vehicle but object will be Car
vehicle.start(); //Car's start called because start() is overridden method
}
}
class Vehicle
{
public void start()
{
System.out.println("Inside start method of Vehicle");
}
}
class Car extends Vehicle
{
@Override
public void start()
{
System.out.println("Inside start method of Car");
}
}
Output: Inside start method of Car
Java instanceof
The java instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because 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.
- class Simple1{
- public static void main(String args[]){
- Simple1 s=new Simple1();
- System.out.println(s instanceof Simple1);
- }
- }
Another example of java instanceof operator
- class Animal{}
- class Dog1 extends Animal{
-
- public static void main(String args[]){
- Dog1 d=new Dog1();
- System.out.println(d instanceof Animal);
- }
- }
class
Dog2{
public static void main(String args[]){
Dog2 d=null;
System.out.println(d instanceof Dog2);
}
}
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).
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.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
- Abstract class (0 to 100%)
- Interface (100%)
Abstract class in Java
A class that is declared as abstract is known as
abstract class. It needs to be extended
and its method implemented. It cannot be instantiated.
Example abstract class
abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method. |
Example abstract method
- abstract void printStatus();
Example of abstract class that has abstract method
In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class.
- abstract class Bike{
- abstract void run();
- }
- class Honda4 extends Bike{
- void run(){System.out.println("running safely..");}
- public static void main(String args[]){
- Bike obj = new Honda4();
- obj.run();
- }
- }
running safely..
File: TestAbstraction1.java
- abstract class Shape{
- abstract void draw();
- }
-
- class Rectangle extends Shape{
- void draw(){System.out.println("drawing rectangle");}
- }
- class Circle1 extends Shape{
- void draw(){System.out.println("drawing circle");}
- }
-
- class TestAbstraction1{
- public static void main(String args[]){
- Shape s=new Circle1();
- s.draw();
- }
- }
drawing circle
Abstract class having constructor, data member, methods etc.
An abstract class can have data member, abstract method, method body, constructor and
even main() method.
File: TestAbstraction2.java
-
- abstract class Bike{
- Bike(){System.out.println("bike is created");}
- abstract void run();
- void changeGear(){System.out.println("gear changed");}
- }
-
- class Honda extends Bike{
- void run(){System.out.println("running safely..");}
- }
- class TestAbstraction2{
- public static void main(String args[]){
- Bike obj = new Honda();
- obj.run();
- obj.changeGear();
- }
- }
-
bike is created
running safely..
gear changed
Rule: If there is any abstract method in a class, that class must be abstract.
class Bike12{
abstract void run();
} //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.
- interface A{
- void a();
- void b();
- void c();
- void d();
- }
-
- abstract class B implements A{
- public void c(){System.out.println("I am c");}
- }
-
- class M extends B{
- public void a(){System.out.println("I am a");}
- public void b(){System.out.println("I am b");}
- public void d(){System.out.println("I am d");}
- }
-
- class Test5{
- public static void main(String args[]){
- A a=new M();
- a.a();
- a.b();
- a.c();
- a.d();
- }}
Output:I am a
I am b
I am c
I am d
Interface in Java
An
interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in java is
a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and multiple
inheritance in Java.
Java Interface also
represents IS-A relationship.
It cannot be instantiated just like abstract class.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
- It is used to achieve abstraction.
- By interface, we can support the functionality of multiple inheritance.
- It can be used to achieve loose coupling.
The java compiler adds public and abstract keywords before the interface method. More, it adds public, static and final keywords before data members.
In other words, Interface fields are public, static and final by default, and methods are public and
abstract.

Printable interface has only one method, its implementation is provided in the A class.
- interface printable{
- void print();
- }
- class A6 implements printable{
- public void print(){System.out.println("Hello");}
-
- public static void main(String args[]){
- A6 obj = new A6();
- obj.print();
- }
- }
Java Interface Example: Drawable
In this example, Drawable interface has only one method. Its implementation is provided by Rectangle and Circle classes. In real scenario, interface is defined by someone but implementation is provided by different implementation providers. And, it is used by someone else. The implementation part is hidden by the user which uses the interface.
File: TestInterface1.java
-
- interface Drawable{
- void draw();
- }
-
- class Rectangle implements Drawable{
- public void draw(){System.out.println("drawing rectangle");}
- }
- class Circle implements Drawable{
- public void draw(){System.out.println("drawing circle");}
- }
-
- class TestInterface1{
- public static void main(String args[]){
- Drawable d=new Circle();
- d.draw();
- }}
Output:
Q) Multiple inheritance is not supported through class in java but it
is possible by interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in case
of class because of ambiguity. But it is supported in case of interface because there
is no ambiguity as implementation is provided by the implementation class. For example:
- interface Printable{
- void print();
- }
- interface Showable{
- void print();
- }
-
- class TestInterface3 implements Printable, Showable{
- public void print(){System.out.println("Hello");}
- public static void main(String args[]){
- TestInterface3 obj = new TestInterface3();
- obj.print();
- }
- }
Output:
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 .
- interface Printable{
- void print();
- }
- interface Showable extends Printable{
- void show();
- }
- class TestInterface4 implements Showable{
- public void print(){System.out.println("Hello");}
- public void show(){System.out.println("Welcome");}
-
- public static void main(String args[]){
- TestInterface4 obj = new TestInterface4();
- obj.print();
- obj.show();
- }
- }
Java 8 Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method.
Let's see an example:
File: TestInterfaceDefault.java
- interface Drawable{
- void draw();
- default void msg(){System.out.println("default method");}
- }
- class Rectangle implements Drawable{
- public void draw(){System.out.println("drawing rectangle");}
- }
- class TestInterfaceDefault{
- public static void main(String args[]){
- Drawable d=new Rectangle();
- d.draw();
- d.msg();
- }}
Java 8 Static Method in Interface
Since Java 8, we can have static method in interface. Let's see an example:
File: TestInterfaceStatic.java
- interface Drawable{
- void draw();
- static int cube(int x){return x*x*x;}
- }
- class Rectangle implements Drawable{
- public void draw(){System.out.println("drawing rectangle");}
- }
-
- class TestInterfaceStatic{
- public static void main(String args[]){
- Drawable d=new Rectangle();
- d.draw();
- System.out.println(Drawable.cube(3));
- }}
Q) What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation.
-
- public interface Serializable{
- }
Nested Interface in Java
Note: An interface can have another interface i.e. known as nested interface. We will learn it in detail in the nested classes chapter. For example:
- interface printable{
- void print();
- interface MessagePrintable{
- void msg();
- }
- }
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.
Abstract class | Interface |
1) Abstract class can have abstract and non-abstractmethods. | Interface can have only abstract methods. Since Java 8, it can have default and static methods also. |
2) Abstract class doesn't support multiple inheritance. | Interface supports multiple inheritance. |
3) Abstract class can have final, non-final, static and non-static variables. | Interface has only static and final variables. |
4) Abstract class can provide the implementation of interface. | Interface can't provide the implementation of abstract class. |
5) The abstract keyword is used to declare abstract class. | The interface keyword is used to declare interface. |
6) Example:
public abstract class Shape{
public abstract void draw();
} | Example:
public interface Drawable{
void draw();
} |
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%).
Example of abstract class and interface in Java
Let's see a simple example where we are using interface and abstract class both.
-
- interface A{
- void a();
- void b();
- void c();
- void d();
- }
-
-
- abstract class B implements A{
- public void c(){System.out.println("I am C");}
- }
-
-
- class M extends B{
- public void a(){System.out.println("I am a");}
- public void b(){System.out.println("I am b");}
- public void d(){System.out.println("I am d");}
- }
-
-
- class Test5{
- public static void main(String args[]){
- A a=new M();
- a.a();
- a.b();
- a.c();
- a.d();
- }}
Comments
Post a Comment