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
PQR.java
TestMain.java
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.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.