Method Overriding in Java

Method Overriding in Java

Method Overriding

If we define the same name for a subclass(child class) and its superclass(parent class) and when the object is created to the subclass, then the method of subclass overrides the superclass method. this is called method overriding

In brief, if we declare a method to a subclass, which is already present in the parent class, Overriding can be done now, where the subclass can give its own implementation to the method which is already present inside the parent class

info

Method overriding is used for runtime polymorphism

Example

class base{
void show(){
System.out.println("Base Method");
}
}
class child extends base{
void show(){
System.out.println("Child Method");
}
}
class override{
public static void main(String[] args){
child obj=new child();
obj.show();
}
}

Output

Child Method

In the above example ,we created a object for the child class ,when show method is called then parent class show( ) is ovridden with the child class show( ),so the output will be Child MEthod

Dynamic Method Dispatch (Runtime Polymorphism)

The overriding is possible in run time and this is called dynamic method dispatch.

A parent class reference variable will be pointed to the child class object. Then the overridden method will be determined at the run time. this is also known as Upcasting

Syntax

class X{}
class Y extends X{}

we created a class named X,and we have created a child class named Y from parent class X

X ref;

we are now creating a ref reference varibale for parent class X

ref=new Y();

created an object for the Y class using reference variable, this is known as up casting

Example

class Base{
void draw(){System.out.println("Base Method");}
}
class child1 extends Base{
void draw(){System.out.println("Child1 MEthod");}
}
class child2 extends Base{
void draw(){System.out.println("Child2 MEthod");}
}
class child3 extends Base{
void draw(){System.out.println("Child3 MEthod");}
}
class poly{
public static void main(String args[]){
Base b;
b=new child1();
b.draw();
b=new child2();
b.draw();
b=new child3();
b.draw();
}
}

Output

Child1 MEthod
Child2 MEthod
Child3 MEthod
Last updated on by vishal devxo