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.
obj
is a reference of type Item
hence the first 20 since the value of cost
field of Item
is 20. The second value is 10
because the runtime type of obj
is Bolt
and hence getCost()
invokes getCost
of Bolt
class (since Bolt
extends Item
).
In short, runtime polymorphism is applicable to only instance members (method overriding) and not instance fields.