File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inheritance

 
Lovleen Gupta
Ranch Hand
Posts: 63
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Lovleen Gupta
Ranch Hand
Posts: 63
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Marc.
It was ver y helpful.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic