class First {
public String str = "first string";
public String value() {
return this.str;
}
public String str1 = value();
}
class Second extends First {
public String str = "second string";
public String value() {
return this.str;
}
public String str1 = value(); public static void main(String h[]){
First first = new Second();
System.out.println( "first.value() = " + first.value() );
System.out.println( "first.str = " + first.str );
System.out.println( "first.str1 = " + first.str1 ); }
}
Resolution of the member variable depends upon the type of the reference variable.
Resolution of member method (or instance method) depends upon the object (like
new Second() in your example) pointed by the reference variable.
so
first.str1 will resolve to a variable beloging to the class named First Now the reason the first.str1 gives you null is because
str1 (of class First) does not have a constant value. Infact it gets the value by executing the method value() which is an instance method belonging to class First. Since the instance of the class First is not created it cannot access this.str (return statement of that method) and hence first.str1 results into null In your example though the type of the variable is of type First but the object its points to belongs to the class Second.
I hope, the above explaination solves your query ...
[ March 12, 2003: Message edited by: Manish Sachdev ]
[ March 12, 2003: Message edited by: Manish Sachdev ]
[ March 12, 2003: Message edited by: Manish Sachdev ]