Practical-24
Write a java program which shows the Method Overriding.
-
Introduction
Method overriding is an important concept of object-oriented programming (OOP), which allows a subclass to provide a specific implementation of a method that is previously defined by one of its super classes. By using method overriding, it becomes possible for two classes related by inheritance to have methods with the same name. In Java, when a method in a subclass has the same name, same parameters, and same return type as a method in its superclass, then the method in the subclass is said to override the method in the superclass.
Code
class Parent
{
public void show()
{
System.out.println("Show method of parent class");
}
}
class Child extends Parent
{
@Override
public void show()
{
System.out.println("Show method of child class");
}
}
public class Main
{
public static void main(String[] args)
{
Parent p = new Child();
p.show();
}
}
Output
Show method of child class
In the above program, we have a Parent class which contains a show() method. We have a subclass Child which extends the Parent class. The Child class overrides the show() method of the Parent class. We create an instance of the Child class, and assign it to the Parent type reference p. This process of overriding a method is also known as Dynamic Method Dispatch.