Java Method Overriding - The Coding Shala
Home >> Learn Java >> Java Method Overriding
Java Method Overriding
We know Inheritance is useful in Java. A subclass inherits all properties of super class so we don't need to write methods again but sometimes we need to provide the specific implementation of a method which is already provided by its superclass. If a child class has the same method as declared in the parent class then it is known as method overriding in Java.
Point to remember: Method overriding is used to achieve runtime polymorphism(will see in later chapters).
Rules for Java Method Overriding
The following are some rules to follow to achieve the method overriding:
- The method must have the same name as in the parent class.
- The method must have the same parameter as in the parent class.
- There must be an IS-A relationship(Inheritance).
Example of Method Overriding
The following is a simple example of method overriding in java:
NOTE: Here @Override annotation is not required to use. It informs the compiler that the element is meant to override. It helps to prevent errors.
Private and Final methods can not be overridden. We will get compile-time errors. The following example explains it:
Protected methods can be overridden and can be made public. The following example explains it:
Static methods can not be Overridden. The main() method is also static method so main() also can not be overridden.
We can declare static methods with the same signature in the subclass as a static method in base class but it is not considered overriding. The method in the derived class hides the method in the base class. It is known as method hiding.
The following example shows method hiding in java:
We can also call the parent class's method in the Overriding method using a super keyword. The following example shows it:
NOTE: Constructor can not be overridden. The constructor name must always be the same as the class name.
Other Posts You May Like