Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing instance members in constructors

I read in a book that instance members are accessible only after the super constructor runs.

I stumbled upon the following code:

class Parent {

    Parent() {
        printIt();
    }

    void printIt() {
        System.out.println("I'm in a overridden method. Great.");
    }
}

class Child extends Parent {

    int i = 100;

    public static void main(String[] args) {
        Parent p = new Child();
        p.printIt();
    }

    void printIt() {
        System.out.print(i + " ");
    }
}

and it prints:

0 100

My question would be:

If instance members are accessible only after the super constructor runs, then why is it that upon execution of the printIt( ) method of class Parent, (which in fact is Child's printIt( ) due to polymorphism), it was able to access the uninitialized instance variable i of Child even though the constructor of Parent has not yet finished executing?

What am I missing?

like image 983
amor214 Avatar asked Dec 08 '22 21:12

amor214


1 Answers

I read in a book that instance members are accessible only after the super constructor runs.

Your book is wrong (if that's what it really says). They are accessible at all times once construction has started. However they are not initialized until after the super constructor has run. So what you printed was the default value: null, zero, or false.

like image 129
user207421 Avatar answered Dec 11 '22 10:12

user207421