public class Shadow {
public static void main(
String s[]) {
S1 s1 = new S1();
S2 s2 = new S2();
System.out.println(s1.s); // prints S1
System.out.println(s1.getS()); // prints S1
System.out.println(s2.s); // prints S2
System.out.println(s2.getS()); // prints S2
s1 = s2;
System.out.println(s1.s); // prints S1, not S2 -
// since variable is resolved at compile time
System.out.println(s1.getS()); // prints S2 -
// since method is resolved at run time
}
}
class S1 {
public String s = "S1";
public String getS() {
return s;
}
}
class S2 extends S1{
//public String s = "S2";
}
here even after assigning variable s1 to s2 's1.s' still prints s1 and not s2.the reason for this is variables are resolved at compile time.
but in the following example,
after s2 being assigned to s1 it's value got changed
public class Shadow1 {
String s="rajini";
public static void main(String s[]) {
Shadow1 s1 = new Shadow1();
Shadow1 s2 = new Shadow1();
s1.s="s1";
s2.s="s2";
System.out.println(s1.s); // prints S1
System.out.println(s2.s); // prints S2
s1 = s2;
System.out.println(s1.s); // prints S1, not S2 -
// since variable is resolved at compile time
}
}
please clarify this doubt.iam very much confused.