Method Overriding In JAVA | Core Java Tutorial | Minigranth
Method Overriding In Java : Introduction
Method overriding in Java is a way to achieve polymorphism. Recall, that we had defined polymorphism as follows : “Polymorphism is the ability of a message to take more than one form”.
Method overriding sticks to above definition.
Method Overriding In Java : Rules
There are two basic rules which need to be followed while applying the concept of method overriding in java. These are :
Method in parent class and child class should have same name and same parameters list.
There should exists inheritance between classes.
Hence method overriding is when a method in subclass has same name and same parameters(signature) as that of the parent class, then the method in subclass is said to override the method of parent class.
When we call the overridden method using child class object then it will always refer to child class method.
Method Overriding In Java : Why ?
Method Overriding in java is actually useful in providing specific implementation of a method that is already provided in parent class.
The implementation in child class will override the implementation of parent class.
The version of method that is executed will be determined by the object that is used to invoke it.
Suppose you invoke the method with parent class object then, method of parent class will be executed and if you invoke method with child class object then overridden method will be executed.
Method Overriding In Java : Example
Let's discuss this concept with the help of an example now.