Method overriding
It is used when a class that extends from another class wants to use most of the feature of the parent class and wants to implement specific functionality in certain cases.
It is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super classes or parent classes.
The implementation in the subclass overrides (replaces) the implementation in the super-class by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class.
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the super-class overrides the super-class's method.
Overriding is a feature that is available while using Inheritance.
This way the new method masks the parent method and would get invoked by default.
class Thought {
public void message() {
System.out.println("I feel like I am diagonally parked in a parallel universe.");
}
}
public class Advice extends Thought {
@Override // @Override annotation in Java 5 is optional but helpful.
public void message() {
System.out.println("Warning: Dates in calendar are closer than they appear.");
}
}
Return type in method Overriding
Before Java 5.0, when you override a method, both parameters and return type must match exactly.
In Java 5.0, it introduces a new facility called covariant return type, override a method with the same signature but returns a subclass of the object returned.
A method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the super-class.
After JDK 1.5, java supports covariant returns, that is, the specialization of the return type to a subtype.
A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2, if and only if the following conditions hold:
· If R1 is void then R2 is void.
· If R1 is a primitive type, then R2 is identical to R1.
· If R1 is a reference type then:
· R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion, or
· R1 = |R2|
No comments:
Post a Comment