Method Overriding in Java
Java Programming Language / Class, Object and Methods in java
1212
Method Overriding in Java
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.
Program:
// 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(); } }
Output:
chis is child class Press any key to continue . . .
Explanation:
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".
This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.