While exploring for scjp questions, I came across this behaviour which I found strange.
I have declared two classes Item and Bolt as follows:
class Item {
int cost = 20;
public int getCost() {
return cost;
}
}
class Bolt extends Item {
int cost = 10;
public int getCost() {
return cost;
}
}
and tried to access the value of cost twice
public class Test {
public static void main(String[] args) {
Item obj = new Bolt();
System.out.println(obj.cost);
System.out.println(obj.getCost());
}
}
The output I get is 20 10.
I can’t understand how this happens.
objis a reference of typeItemhence the first 20 since the value ofcostfield ofItemis 20. The second value is10because the runtime type ofobjisBoltand hencegetCost()invokesgetCostofBoltclass (sinceBoltextendsItem).In short, runtime polymorphism is applicable to only instance members (method overriding) and not instance fields.