Method Overriding in Java - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Random Posts


When a class inherits a method from super class, the method can be redefined in this class (with the same method signature), which overwrites the previous logic. This technique is known as method overriding.

Instead of taking the previous example, let us discuss it with a simple program.

ABC.java
public class ABC { void print() { System.out.println("I am in ABC."); } }
PQR.java
public class PQR extends ABC { void print() { System.out.println("I am in PQR."); } }
TestMain.java
public class TestMain { public static void main(String[] args) { ABC abc = new ABC(); abc.print(); PQR pqr = new PQR(); pqr.print(); } }

In the above example, we have defined class ABC and class PQR, where class PQR inherits class ABC. The print method is defined in the ABC class as well as in PQR class. Hence, you have to understand how it works?

When an instance of the ABC class is created in the main method, naturally, the print method call will execute the method defined in the ABC class. When an instance of PQR class is created, this class contains a print method and it inherits another print method from the ABC class with the same signature of the method. Hence, which one will be executed - the method defined in this class or the method defined in the parent class?

Here, the answer is: the print method defined in PQR class will be executed. This local method of PQR class will override the inherited method.


Happy Exploring!

No comments:

Post a Comment