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 //not recommended public void aMethod() { //overrides aMethod in Superclass aVariable = false; super.aMethod(); System.out.format("%b%n", aVariable); System.out.format("%b%n", 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:The following example illustrates how to use thefalse truesuper
keyword to invoke a superclass's constructor. Suppose you are writing a transaction-based system and need to throw a checked exception if the transaction fails. Such an exception should include an informative message and a reference to the cause of the problem, another exception, checked or unchecked (Throwable
).The line in boldface is an explicit superclass constructor invocation that calls a constructor provided by the superclass,public final class TransactionFailedException extends Exception { static final long serialVersionUID = -8919761703789007912L; public TransactionFailedException(Throwable cause) { super("Transaction failed", cause); } }Exception
.Exception
has four constructors and this particular one invokes the version that takes aString
argument and aThrowable
argument. If present, an explicit superclass constructor invocation must be the first statement in the subclass constructor initialization of the superclass must always be performed before initializing the subclass. If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass (or gives a compile-time error if no such constructor is available).
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.