saravanan
saravanan

Reputation: 5407

instance variable and methods are not allowed in call to super constructors

Why are instance variable and methods not allowed in call to super constructors or the call to overloaded constructors?

Upvotes: 1

Views: 826

Answers (3)

dimitrisli
dimitrisli

Reputation: 21391

Because at the time the super is getting called, instance variables don't exist yet! Wherever there is a new statement to create an object of that class in the heap, its constructor first would call super() -by default- or your super(..) -in case you specify one- and then would continue by initializing the object's fields.

Upvotes: 0

Riduidel
Riduidel

Reputation: 22292

Because when you call the super constructor, it's to build parent class. Due to class hierarchies, your child class is not yet constructed when building parent class. let's illustrate with an example

class Parent() {
    protected String s;
    public Parent(String s) {
        System.out.println("parent created with "+s);
        this.s = s; // don't do this at home, kids, one letter variables stinks like hell
    }
}

class Child extends Parent {
    public Child(String s) {
        // don't try to put an instruction here, it's impossible due to the mandatory call to super as first instruction
        super(s);
        System.out.println("child created with "+s);
    }
}

When you call new Child("I'm the king of the world"), the first method called is in fact Parent(String), as System.out will show up. And that's quite normal, because as Child is a subclass of Parent, the underlying Parent object must be created before the Child object is.

What does this has to do with instance variables ? Well, they exist only when object is created. As a consequence, instance variables of Child are not available while creating a Parent object. In the following example

class OtherChild extends Parent {
    private String prefix = "some ";
    public OtherChild(String s) {
        // don't try to put an instruction here, it's impossible due to the mandatory call to super as first instruction
        super(prefix+s);
        System.out.println("child created with "+s);
    }
}

You'll have an initialization error because the prefix field is not initialized when calling suoper constructor, as the Child object in fact does not yet exists at this precise time. Was my explanation clear enough ?

Upvotes: 1

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43098

Because the object is not initialized completely. The object can be in the inconsistent state which is error prone and hard to discover. Static methods can be called because they are independent of the object state.

Upvotes: 0

Related Questions