Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why exactly do subclass constructors have to explicitly call super class constructors? [duplicate]

Tags:

java

Possible Duplicate:
Why does this() and super() have to be the first statement in a constructor?

Why exactly do subclass constructors have to explicitly call super class constructors? What is the reason for this?

like image 358
John W Avatar asked Jan 10 '13 03:01

John W


2 Answers

They don't.

If you don't explicitly call a superconstructor, it's equivalent to calling the parameterless superconstructor.

public class Sub
{
    public Sub()
    {
        // Do some stuff
    }
}

is equivalent to:

public class Sub
{
    public Sub()
    {
        super();
        // Do some stuff
    }
}

You do explicitly have to call a superconstructor if you want to specify arguments. That's pretty reasonable, IMO - would you really want the compiler guessing which arguments you wanted to supply?

like image 188
Jon Skeet Avatar answered Oct 04 '22 20:10

Jon Skeet


As mentioned above, you only have to invoke a super constructor if there isn't a default constructor in the parent class.

This is required because the parent class must be initialized by one of its constructors, and if there isn't a default constructor, the java compiler has no way of knowing which constructor to call, or what parameters need to be passed.

To better understand why at least one constructor in the parent must be called, consider the following:

class Person {
    private Person mother;
    private Person father;

    public Person(Person mother, Person father) {
        assert mother != null && father != null: "Parents can't be null!";

        this.mother = mother;
        this.father = father;
    }

    public boolean hasAnyLivingParents() {
        return mother.isAlive() || father.isAlive();
    }

    public boolean isAlive() { return true; }
}

If you create a Person directly, you must specify the mother and father of the person, and the hasAnyLivingParents() method expects these to be specified.

Now, consider you have a subclass, Employee, and you don't care about the parents of an Employee, so you want to write something like this:

class Employee extends Person {
    double salary;

    public Employee(double salary) { 
        this.salary = salary;
    }
}

This won't compile because we don't call a constructor of Person, and there isn't a default constructor. If this did compile, calling (new Employee(50000d)).hasAnyLivingParents() would always throw a NullPointerException, since nothing even initialized the mother and father fields.

In short, java requires that every class be initialized by some constructor. If there isn't a default constructor on a class, one of its other constructors must be called for the object to be initialized.

like image 28
Yona Appletree Avatar answered Oct 04 '22 22:10

Yona Appletree