Java: Calling super()

super() calls the constructor of the base class.

... new Dog(); class Dog extends Animal { Dog() { super(); } } class Animal { Animal() { } }

Not to be confused with super.someMethod(). See Calling super.someMethod().

Another Example

Here's an expanded version with printouts and constructor arguments.

class Animal {
    public Animal(String arg) {
        System.out.println("Constructing an animal: " + arg);
    }
}

class Dog extends Animal {
    public Dog() {
        super("From Dog constructor");
        System.out.println("Constructing a dog.");
    }
}

public class Test {
    public static void main(String[] a) {
        new Dog();
    }
}

Prints the following:

Constructing an animal: From Dog constructor
Constructing a dog.

The Fine Print

Comments

Be the first to comment!