- In Java, method overriding occurs when a subclass (child class) has the same method as the parent class.
- Overriding is a feature that allows a subclass or child class to implement a method that is already provided by one of its super-classes or parent classes.
- When a subclass’s method has the same name, parameters, signature, and return type (or subtype) as a method in its superclass, the subclass’s method is said to override the superclass’s method.
- Method overriding is one of the ways by which java achieves Run Time Polymorphism.
Application of Java Method Overriding:
- Method overriding is a technique for providing a custom implementation of a method that is already provided by its superclass.
- For runtime polymorphism, method overriding is used.
Java Method Overriding Rules:
- The method’s name must match that of the parent class.
- The parameter must be the same as in the parent class.
- An IS-A relationship is required (inheritance).
Method Overriding Example:
class Bank{
int getRateOfInterest()
{
return 0;
}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank{
int getRateOfInterest()
{
return 9;
}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Points to remember:
- The super keyword can be used to invoke the parent class method in an overriding method.
- We can’t override the constructor because parent and child classes can’t have the same constructor name (The constructor name must always be the same as the Class name).
- Overriding a static method is not possible. Runtime polymorphism can prove it, so we’ll learn it later.
- A static method is bound to a class, whereas an instance method is bound to an object, therefore a static method cannot be overridden.
- Because main is a static method, it cannot be overridden.
Note: also read about the Method Overloading
Follow Me
If you like my post please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Leave a Comment