The super Keyword


The super keyword refers to superclass (parent) objects. If a class is inheriting the properties of another class and if the members of the superclass have the names same as the subclass, to differentiate these variables we use super keyword as follows:
     super.variable
     super.method( );
If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the superclass. But if you want to call a parameterized constructor of the superclass, you need to use the super keyword as follows:
     super( values );
MySuper.java (the super keyword)
public class MySuper {
  public static void main( String args[ ] ) {
    // Create a Dog object.
    Animal myDog = new Dog( args[0] );
    System.out.print( myDog.aname + " " );
    // Call the method on the Dog object.
    myDog.animalSound( );
  }
}

// Superclass (parent)
class Animal {
  String aname = "Rocky";
  Animal( String name ) { aname = name; }
  public void animalSound( ) { System.out.print( "barks" ); }
}

// Subclass (child)
class Dog extends Animal {
  // Call the superclass constructor.
  Dog( String name ) { super( name ); }
  // Call the superclass method.
  public void animalSound( ) { super.animalSound( ); }
}
shell> java MySuper  

Output:           Result:




      Let the cat out of the bag.