superclass can't get a value of an initialized variable
How can I override a get method called by a superclass constructor without setting the variable to static or final?
E.G!
publicclass Super
{
publicstaticfinal String name="Super";
public Super(){
int length=getLength();
}
publicint getLength(){
final String methodName ="getLength";
System.out.println(name+"."+methodName);
return 333;
}//getImg
}
publicclass Sub
extends Super
{
privateint initialized=40;
publicstaticfinal String name="Sub";
publicstaticvoid main(String[] args){
Sub iNstance=new Sub();
int length=iNstance.getLength();
}
publicint getLength(){
final String methodName ="getLength";
System.out.println(name+"."+methodName+" initialized="+this.initialized);
return -111;
}
public Sub(){
super();
}
}
When I run the Sub, then the output is:
Sub.getLength initialized=0
Sub.getLength initialized=40
Is there a way to get the value of this initialized variable from the superclass constructor without setting the variable static or final?
Any reference to the tutorial will be appreciated.
Thanks
[2814 byte] By [
astlandaa] at [2007-10-3 3:00:12]

> How can I override a get method called by a
> superclass constructor without setting the variable
> to static or final?
I don't see how "static" or "final" would help. You are not supposed to do what you want to do - in fact, if you call a method in your own class from the c'tor, the method should be declared final or private.
> When I run the Sub, then the output is:
> > Sub.getLength initialized=0
> Sub.getLength initialized=40
>
Remember that objects are constructed in order of the object hierarchy. i.e. Any initialization of member variables or code in the constructor is not executed until after all superclass construction has completed. Therefore, initialized is not assigned the value of 40 until after the superclass construction has completed. As you can see, polymorphism causes the subclass getLength() method to be called. However, since it is called from the superclass, the initialized variable is still in its original state, which is 0.
> How can I override a get method called by a
> superclass constructor without setting the variable
> to static or final?
>
> E.G!
> [code]
> public class Super
> {
> public static final String name="Super";
>
> public Super(){
> int length=getLength();
> }
>
Each time I read the code, I get lost here. why are you doing this in the constructor. Constructor is not like any other method. It has a specific purpose. To provide the object a state i.e., to initialize the object. Now the int length you are putting a value in is a local variable to the constructor, doesnt make sense to me. Secondly the variables in a constructor should be initialized by values provided in the parameter list . If it is not there there is no point in initalizing it in c'tor.