• Post Reply Bookmark Topic Watch Topic
  • New Topic

Please clarify, if possible.  RSS feed

 
Abrahim Daver
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was surprised to see output of following programm



AS

Mobile.showDevice,null Mobile.showDevice,Mobile.device Mobile.showDevice,Mobile.device



Will someone please clarify, why output is like this.
Thanks
AD
[ July 20, 2005: Message edited by: Abrahim Daver ]
 
Abrahim Daver
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

[ July 20, 2005: Message edited by: Abrahim Daver ]
 
Maulin Vasavada
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Abrahim

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

regards
maulin
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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."
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!