Java Reference
In-Depth Information
The following sequence of events occurs:
1. The eat method in Lion is invoked, which prints “Inside Lion”.
2. The eat method in Mammal is called on line 4 using the super reference, which causes
Inside Mammal ” to be displayed.
Therefore, the output is
Inside Lion
Inside Mammal
The super Reference
Just like every object has a reference to itself via the this keyword, every object has a
reference to its parent object via the super keyword. A child object can actually use the
this reference to access parent class members, but there are situations where the child
class must use super to access a parent fi eld or method.
For example, suppose in the Lion class we had the following eat method:
10. public class Lion extends Mammal {
11. public int eat(String something) {
12. System.out.println(“Inside Lion”);
13. return this.eat(something);
14. }
15. }
The call to this.eat on line 13 is a recursive call that causes control to jump to line 11,
which creates an infi nite recursion eventually resulting in a stack overfl ow error. In this
example, if the Lion wants to call eat in Mammal , it must use the super reference.
Covariant Return Types
Before Java 5.0, it was required that the overriding method in the child have the same
return type as the overridden method in the parent. Java 5.0 introduced covariant return
types , which allows the overriding method to return a data type that is a child of the return
type in the parent class.
For example, the following Child class successfully overrides the doSomething method
in Parent because FileOutputStream is a child of OutputStream :
//Parent.java
public class Parent {
public OutputStream doSomething(int x, String s) {
//do something
}
Search WWH ::




Custom Search