The Keyword super

The keyword super is used similarly to the keyword this. The keyword this, if you remember from the description earlier, provides us with a reference to the object we are currently in, which is useful for things such as accessing an instance variable instead of a local variable when they share the same identifier name. The keyword super is used to access the super class of the object that you are currently in. There are two ways that we can use the keyword super, one for calling a constructor of the super class and the other for accessing methods and attributes of the super class. As we saw in the previous example, we called the constructor of the Creature class from within the constructor of the Alien class.

// default call to the super class constructor super();
// if a super class constructor took two parameters of type String super("Thank you", "for all your support");

This is general practice, as it is most often the case that you need to initialize super class members also, as they form the base of your object. You may also need to access members of the super class, which you cannot access from the current object because there exists an overriding version of that member in the current object. For example, in the Alien class there is a speak method, but there is also a speak method in its super class Creature. The speak method in the Alien class replaces the speak method in the Creature class, but it does not remove it. What if we wanted to access this method instead? You would use the keyword super in the Alien object to access the speak method in the super class Creature instead of the speak method in its own class.

// Inside an Alien object, use the speak method defined in // the Creature class instead super.speak();

As you can see, we use the keyword super similarly to how we used the keyword this earlier. Note that you can only use the keyword super to access the immediate super class object of an object, and this access does not allow you to view inaccessible members of the super class, such as private members of the super class, under any circumstances. So using super.greeting in an Alien object will not work, and you will get a compiler error. The keyword super is for accessing constructors and overridden members of the super class of an object.


It is not possible to chain super keywords to access above one hierarchical class level. Calling super.super.toString() in the last defined Alien class would not call Object.toString(); it would not even compile.