Method Overriding in Java is a mechanism by which a subclass provides its own implementation of a method that is already defined in its parent class. It is a key concept in object-oriented programming that allows for polymorphism, which means that objects of different classes can be treated as if they were objects of a single class. In Java, method overriding is accomplished by creating a method with the same signature (i.e., name, parameters, and return type) as the parent class method in the subclass. When the method is called on an object of the subclass, the overridden method in the subclass is executed instead of the method in the parent class.
// Example of method overriding
class Parent{
void display(){
System.out.println("parent class");
}
}
class Child extends Parent{
void display(){
System.out.println("This is child class");
}
public static void main(String args[]){
Child obj = new Child();
obj.display();
}
}
chis is child class
Press any key to continue . . .
The given code is an example of method overriding in Java. It defines two classes - Parent and Child. The Child class extends the Parent class and overrides its display() method.
In the Parent class, the display() method simply prints "parent class" to the console. In the Child class, the display() method is overridden to print "This is child class" instead.
In the main() method, an object of the Child class is created and the display() method is called on it. Since the Child class overrides the display() method, the output will be "This is child class".
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.