Using the super Keyword

The super keyword is used from the subclass to call fields, methods and constructors in the superclass.

Using super with Constructors

When the subclass is being created, the superclass constructor is called first. Lets see any example :

Animal.java

public class Animal {
    Animal(){
        System.out.println("Animal created");
    }
}

Cat.java

public class Cat extends Animal {
    Cat(){
        System.out.println("Cat created");
    }
}

Main.java

public class Main {

    public static void main(String[] args) {
      Cat cat = new Cat();
    }
}

Output:

Animal created

Cat created

You will notice from the output that the superclass Animal constructor is called first and then the Cat class. This is all good using the default, no-argument contructor. What happens if we create a custom constructor?

To call and initialize the superclass contructor we can use the super keyword. Let's see an example :

Animal.java

public class Animal {
    Animal(String name){
        System.out.println("I am " + name + " the Animal");
    }
}

Cat.java

public class Cat extends Animal {
    Cat(String name){
        super(name);
        System.out.println("I am " + name +" the Cat");
    }
}

Output :

I am Tim the Animal

I am Tim the Cat

Notice we called the superclass constructor as follows super(name). This calls the superclass contructor and passes in the name parameter.

Using super with Fields and Methods

We can call fields and methods defined in the superclass using the super keyword.

super.fieldName;
super.methodName(param1, param2,...);

results matching ""

    No results matching ""