Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructors and instance variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructors and instance variables" Watch "Constructors and instance variables" New topic
Author

Constructors and instance variables

Gina vernon
Ranch Hand

Joined: Jan 16, 2009
Posts: 108
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

Joined: Dec 23, 2008
Posts: 12
hi..


I think you are right.
Ruben Soto
Ranch Hand

Joined: Dec 16, 2008
Posts: 1032
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:



All code in my posts, unless a source is explicitly mentioned, is my own.
Gina vernon
Ranch Hand

Joined: Jan 16, 2009
Posts: 108
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

Joined: Dec 16, 2008
Posts: 1032
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Constructors and instance variables