< Java Programming < Keywords

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 cannot be called. Only public and protected methods can be called by the super keyword.
  • It is also used by class constructors to invoke constructors of its parent class.
  • Super keyword are not used in static Method.

Syntax:

super.<method-name>([zero or more arguments]);

or:

super([zero or more arguments]);

For example:

Code listing 1: SuperClass.java
1 public class SuperClass {
2    public void printHello() {
3       System.out.println("Hello from SuperClass");
4       return;
5    }
6 }
Code listing 2: SubClass.java
 1 public class SubClass extends SuperClass {
 2    public void printHello() {
 3       super.printHello();
 4       System.out.println("Hello from SubClass");
 5       return;
 6    }
 7    public static main(String[] args) {
 8       SubClass obj = new SubClass();
 9       obj.printHello();
10    }
11 }

Running the above program:

Command for Code listing 2
$Java SubClass
Output of Code listing 2
Hello from SuperClass
Hello from SubClass

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

Code section 1: A lower bound on a wildcard type parameter.
1 public void sort(Comparator<? super T> comp) {
2   ...
3 }

See also:

This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.