class Test{
public static void main(
String [] args){
Base b = new Subclass();
System.out.println(b.x);
System.out.println(b.method());
}
}
class Base{
int x = 2;
int method(){
return x;
}
}
class Subclass extends Base{
int x = 3;
int method(){
return x;
}
}
//Second code
class Test{
public static void main(String [] args){
Base b = new Subclass();
System.out.println(b.x);
System.out.println(b.method());
}
}
class Base{
int x = 2;
//int method(){
// return x;
}
class Subclass extends Base{
int x = 3;
int method(){
return x;
}
}
Output is 2 & 3 as the rule for accessing variables object ref is used and while assessing methods object is used(understandable) but if I change the code by removing method() in base as it is not being referenced by the object b, I get" method not found in class Base error" during compailing " Again If cast object b by changing line to System.out.println(((Subclass)b).method()); it will compaile and output 2 & 3 Can any body explain correctly