Hi,
I found this in one of the mock exams.
class car{
int gearratio = 9;
String method(){return "from car class";}
}
class sportscar extends car{
int gearratio = 7;
String method(){return "from sportscar class";}
public static void main(String[] args){
car a = new sportscar();
System.out.println("gr = " + a.gearratio + " " + a.method());
}
}
the output is , gr = 9 from sportscar class
the explanation given was,the variables are shadowed and methods are overridden. this means that the variable to be selected depends on the declared class of the variable.method to be selected depends on the actual object class the variable is refering to.
in this case, it is fine. But if I change, the method name from method() to method1() in car, then it is failing to compile saying that the method() is not found in car. here is the problem. when a method is overridden, and it is called from an object which refers to the overiding object, then, will it first check in the overridden class or overidding class? if it first checks in overriding class, it should not fail in compilation..