Java Reference
In-Depth Information
Use the
super
keyword to call the original method from inside a method definition. This
keyword passes the method call up the hierarchy, as shown in the following:
void doMethod(String a, String b) {
// do stuff here
super.doMethod(a, b);
// do more stuff here
}
The
super
keyword, similar to the
this
keyword, is a placeholder for the class's super-
class. You can use it anywhere that you use
this
, but
super
refers to the superclass
rather than the current object.
Overriding Constructors
Technically, constructor methods cannot be overridden. Because they always have the
same name as the current class, new constructor methods are created instead of being
inherited. This system is fine much of the time; when your class's constructor method is
called, the constructor method with the same signature for all your superclasses also is
called. Therefore, initialization can happen for all parts of a class that you inherit.
However, when you are defining constructor methods for your own class, you might
want to change how your object is initialized, not only by initializing new variables
added by your class, but also by changing the contents of variables that are already there.
To do this, explicitly call the constructor methods of the superclass and subsequently
change whatever variables need to be changed.
To call a regular method in a superclass, you use
super.
methodname
(
arguments
)
.
Because constructor methods don't have a method name to call, the following form is
used:
super(arg1, arg2, ...);
Note that Java has a specific rule for the use of
super()
: It must be the first statement in
your constructor definition. If you don't call
super()
explicitly in your constructor, Java
does it for you—automatically calling
super()
with no arguments before the first state-
ment in the constructor.
Because a call to a
super()
method must be the first statement, you can't do something
like the following in your overriding constructor:
if (condition == true)
super(1,2,3); // call one superclass constructor
else
super(1,2); // call a different constructor