Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructors and instance variables

 
Gina vernon
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
The study guide says that instance variables/methods cannot be accessed before a call to the class's constructor. But it seems there is no way one would be able to make that error, since you have to call a constructor in order to access instance variables/methods.

Right/wrong?

Thanks.
 
rajendhar gangoni
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi..


I think you are right.
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gina vernon wrote:Hi,
The study guide says that instance variables/methods cannot be accessed before a call to the class's constructor. But it seems there is no way one would be able to make that error, since you have to call a constructor in order to access instance variables/methods.

Right/wrong?

Thanks.

Well, actually you could try to access an instance variable or method defined in the superclass from the subclass' constructor super(...) call. For example:

 
Gina vernon
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ruben Soto wrote:
Well, actually you could try to access an instance variable or method defined in the superclass from the subclass' constructor super(...) call. For example:


Ok,got it. thanks.
 
Ruben Soto
Ranch Hand
Posts: 1032
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gina vernon wrote:
Ruben Soto wrote:
Well, actually you could try to access an instance variable or method defined in the superclass from the subclass' constructor super(...) call. For example:


Ok,got it. thanks.

That's great, Gina!

Yes, the obvious scenario is accessing an instance variable or method through an instance of the class (which will never give you any problems, since in order to have an instance all the instantiation code must have run.) The more insidious scenario is when you are trying to access an instance variable or method from subclass code before the super constructor has run.

However, you can access instance variables in instance variable initializer expressions (provided you don't use illegal forward referencing.)



The trick here is that the compiler will actually make instance initializers a part of the actual constructor code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic