Java Reference
In-Depth Information
4.2.4 The this and super reference operators
Perhaps you need to create a subclass that overrides a method in the base class.
However, you want to take advantage of code already in the overridden method
rather than rewriting it in the overriding method. That is, you want to do every-
thing that the original method did but add some extra functionality to it for the
subclass.
When in a subclass, the special reference variable super always refers to the
superclass object. Therefore, you can obtain access to overridden methods and
data with the super reference. In the following code class Child overrides the
doSomething() method in class Parent but calls the overridden method by
using super.doSomething() :
public class Parent {
int i = 0;
void doSomething () {
i =5;
}
}
class Child extends Parent {
int j = 0;
void doSomething () {
j = 10;
// Call the overridden method
super.doSomething ();
j+= i; // then do something more
}
}
Yo u cannot cascade super references to access methods more than one class
deep as in
j = super.super.doSomething(); // Error!! Not a valid use of
//super
This usage would seem logical but it is not allowed. You can only access the
overridden method in the immediate superclass with the super reference.
Note that you can also “override” data fields by declaring a field in a subclass
with the same name as used for a field in its superclass. This technique is seldom
useful and is very likely to be confusing to anyone using your code. Its use is not
recommended.
 
Search WWH ::




Custom Search