Method Overriding is a type of polymorphism.
It is dynamic type of polymorphism.
In this we have the method with the similar name in both parent class and child class.
But the child class override the method of the parent class when we create object of the child class having the same method.
Method overriding is used to inherit the properties of the parent class but not modifying the method of the parent class.
class Human{
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
obj.eat();
}
}
In the above example, the object of eat method is created using reference of the child class.
So the output will be Boy is eating.
class ABC{
public void disp()
{
System.out.println("disp() method of parent class");
}
public void abc()
{
System.out.println("abc() method of parent class");
}
}
class Test extends ABC{
public void disp(){
System.out.println("disp() method of Child class");
}
public void xyz(){
System.out.println("xyz() method of Child class");
}
public static void main( String args[]) {
//Parent class reference to child class object
ABC obj = new Test();
obj.disp();
obj.abc();
}
}
In this the object of the disp method is created using the reference of the parent class and object is called using both child and the parent class.
So the out will be
disp() method of Child class
abc() method of parent class
0 Comment(s)