|
|
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 usesuperto 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 overridesaMethodand 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 nameaVariablerefers to the one declared inSubClass, which hides the one declared inSuperclass. Similarly, the simple nameaMethodrefers to the one declared inSubclass, which overrides the one inSuperclass. So to refer toaVariableandaMethodinherited fromSuperclass,Subclassmust use a qualified name, usingsuperas shown. Thus, the print statements inSubclass'saMethoddisplay the following:You can also usefalse truesuperwithin 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 forAnimationThreadsets 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 particularThreadconstructor takes aStringthat 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.