The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Classes and Inheritance

Using super

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of super. You can also use super to refer to a hidden member variable. Consider this class, Superclass:
public class Superclass {
    public boolean aVariable;

    public void aMethod() {
        aVariable = true;
    }
}
Now, here's a subclass, called Subclass, that overrides aMethod and hides aVariable:
public 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);
    }
}
Within Subclass, the simple name aVariable refers to the one declared in Subclass, which hides the one declared in Superclass. Similarly, the simple name aMethod refers to the one declared in Subclass, which overrides the one in Superclass. So to refer to aVariable and aMethod inherited from Superclass, Subclass must use a qualified name, using super as shown. Thus, the print statements in Subclass's aMethod display the following:
false
true
The following example illustrates how to use the super 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).
public final class TransactionFailedException extends Exception {
    static final long serialVersionUID = -8919761703789007912L;

    public TransactionFailedException(Throwable cause) {
        super("Transaction failed", cause);
    }
}
The line in boldface is an explicit superclass constructor invocation that calls a constructor provided by the superclass, Exception. Exception has four constructors and this particular one invokes the version that takes a String argument and a Throwable 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).

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.