File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes inheritance 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 "inheritance" Watch "inheritance" New topic
Author

inheritance

Lovleen Gupta
Ranch Hand

Joined: Feb 26, 2007
Posts: 63
Here is one code:

class Uber{
int y = 2;
//static int y = 2;
Uber(int x) {this(); y = y*2;}
Uber(){y++;}
}

class Minor extends Uber{
Minor(){super(y); y=y+3;}
public static void main(String[] args){
new Minor();
System.out.println(y);
}
}


Here it shows error in minor saying - can't reference y before supertype constructor is called.
Can somebody please explain why so?

My understanding says that since y has a default access, it will be accessible to class Minor and hence we can use it.

Please clear my doubt.
Thanks.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Lovleen Gupta:
...My understanding says that since y has a default access, it will be accessible to class Minor and hence we can use it...

This has nothing to do with access controls. It has to do with trying to use the variable before it's initialized.

In main, you are calling the constructor for Minor(). The first line within this constructor is a call to super(int x). The int being passed is y. That's the problem: There is no "y" at this point. The reason is that y is an instance variable in Uber, and until Uber's constructor finishes, there is no Uber instance. Or as the compiler puts it: "cannot reference y before supertype constructor has been called."

On the other hand, if you use the commented-out line and make y static (a class variable), then this will work. The reason is that the Uber class is initialized (making its static members available) when it's loaded, which happens before the constructor call.

To see the order in which these things happen, add some println statements with some static and non-static initializer blocks...

PS: You might find Code Tags and indentation helpful too.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Lovleen Gupta
Ranch Hand

Joined: Feb 26, 2007
Posts: 63
Thanks a lot Marc.
It was ver y helpful.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: inheritance