OOPS in JAVA 13
Method Overriding
When a method in a sub class has same name and type signature as a method in its super class, then the method is known as method overriding.
Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is the abitility to define method that's specific to a particular subclass type.
Usage of Java Method Overriding
1. Method overriding is used to provide specific implementation of a method that is already provided by its super class.
2. Method overriding is used for runtime polymorphism.
Rules for Java Method Overriding
1. method must have same name as in the parent class.
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Example
class Animal
{
public void eat()
{
System.out.println("Generic Animal eating");
}
}
class Dog extends Animal
{
public void eat() //eat() method overriden by Dog class.
{
System.out.println("Dog eat meat");
}
}
As you can see here Dog class gives it own implementation of eat() method. Method must have same name and same type signature.
NOTE : Static methods cannot be overridden because, a static method is bounded with class where as instance method is bounded with object.
Difference between Overloading and Overriding?
Method Overloading | Method Overriding |
Parameter must be different and name must be same. | Both name and parameter must be same. |
Compile time polymorphism. | Runtime polymorphism. |
Increase readability of code. | Increase reusability of code. |
Access specifier can be changed. | Access specifier most not be more restrictive than original method(can be less restrictive). |
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )