Home / Programs / Method Overriding in Java
Programming Example

Method Overriding in Java

👁 1,255 Views
💻 Practical Program
📘 Step by Step Learning
Method overriding is a fundamental concept in object-oriented programming, allowing for the creation of more flexible and modular code. It allows a subclass to provide its own implementation of a method that was already defined in its parent class, resulting in more specific behavior for objects of the subclass. In Java, this is accomplished by creating a method in the subclass with the same signature as the method in the parent class. This allows for the use of polymorphism, which treats objects of different classes as if they were objects of the same class, and is an essential concept in Java programming.

Information & Algorithm

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 Code

 // 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".

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.