Java Programming/Keywords/super

From Wikibooks, open books for an open world
Jump to: navigation, search

super is a keyword.

  • It is used inside a sub-class method definition to call a method defined in the super class. Private methods of the super-class can not be called. Only public and protected methods can be called by the super keyword.
  • It is also used by class constructors to invoke constructurs of its parent class.

Syntax:

super.<method-name>();

For example:

Computer code
public class SuperClass
 {
    public void printHello()
    {
       System.out.println( <code><font style="color:DarkGreen; text-decoration: none; font-weight: bold;">&quot;Hello from SuperClass&quot;</font></code> );
      return;
    }
 }
 //...
 public class SubClass extends SuperClass
 {
    public void printHello()
    {
       super.printHello();
       System.out.println( <code><font style="color:DarkGreen; text-decoration: none; font-weight: bold;">&quot;Hello from SubClass&quot;</font></code> );
      return;
    }
 
    public static main( String[] args )
    {
       SubClass obj = new SubClass();
       obj.printHello();
    }
 }

Running the above program:

Java SubClass

The output:

"Hello from SuperClass"
"Hello from SubClass"

See also:

In Java 1.5 and later, the "super" keyword is also used to specify a lower bound on a wildcard type parameter in Generics.

public void sort(Comparator<? super T> comp) { ... }
Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
In other languages
Sister projects
Print/export