This is due to the sequence in which objects get initialized.
1. all static variables of a class as soon as its refferred 2. all static blocks of the class 3. all parent constructors are initialized in the extension hierarchy 4. instance variables of the class gets initialized 5. rest of the constructor of the class
Here in your example, 1. when first Mobile() constructor gets called, it calls Phone constructor which calls the showDevice method which is overriden in the Mobile class BUT as instance variables of the Mobile class are not yet initialized you get the NULL value in the device variable and you get the first print with null
2. then it returns to the Mobile class and does instance init of Mobile class which will initialize the device var to have Mobile value
3. now the showDevice on Mobile is called where you get the Mobile value in output
4. from the main method again you call showDevice and get the output
Never invoke a non-final instance method in a constructor, as one day that method may be overridden and you will run into a problem if that method relies on a variable which has not been initialized because the subclass's object has yet to be fully constructed.
Change your showDevice1() method to be final or private (which makes it implicitly final) and see what is the output.
Originally posted by Roger Chung-Wee: Never invoke a non-final instance method in a constructor
Since this is the Advanced forum, I'll add "unless the constructor is a template method -- i.e., the non-final instance method is intended to be overridden as a way of customizing the constructor's operation."