Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
If your method overrides one of its superclass's methods, you can invoke the overridden method through the use ofsuper
. You can also usesuper
to refer to a hidden member variable. Consider this class,Superclass
:Now, here's a subclass, calledpublic class Superclass { public boolean aVariable; public void aMethod() { aVariable = true; } }Subclass
, that overridesaMethod
and hidesaVariable
:Withinpublic class Subclass extends Superclass { public boolean aVariable; //hides aVariable in Superclass public void aMethod() { //overrides aMethod in Superclass aVariable = false; super.aMethod(); System.out.println(aVariable); System.out.println(super.aVariable); } }Subclass
, the simple nameaVariable
refers to the one declared inSubClass
, which hides the one declared inSuperclass
. Similarly, the simple nameaMethod
refers to the one declared inSubclass
, which overrides the one inSuperclass
. So to refer toaVariable
andaMethod
inherited fromSuperclass
,Subclass
must use a qualified name, usingsuper
as shown. Thus, the print statements inSubclass
'saMethod
display the following:You can also usefalse truesuper
within a constructor to invoke a superclass's constructor. The following code sample is a partial listing of a subclass ofThread
a core class used to implement multitasking behavior which performs an animation. The constructor forAnimationThread
sets up some default values, such as the frame speed and the number of images, and then loads the images:The line set in boldface is an explicit superclass constructor invocation that calls a constructor provided by the superclass ofclass AnimationThread extends Thread { int framesPerSecond; int numImages; Image[] images; AnimationThread(int fps, int num) { super("AnimationThread"); this.framesPerSecond = fps; this.numImages = num; this.images = new Image[numImages]; for (int i = 0; i <= numImages; i++) { ... // Load all the images. ... } } ... }AnimationThread
, namely,Thread
. This particularThread
constructor takes aString
that sets the name ofThread
. If present, an explicit superclass constructor invocation must be the first statement in the subclass constructor: An object should perform the higher-level initialization first. If a constructor does not explicitly invoke a superclass constructor, the Java runtime system automatically invokes the no-argument constructor of the superclass before any statements within the constructor are executed.
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.