|
|
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 //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 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:The following example illustrates how to use thefalse truesuperkeyword 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.Exceptionhas four constructors and this particular one invokes the version that takes aStringargument and aThrowableargument. 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.