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.
Java does not support multiple inheritance. Multiple inheritance means a class derived from more than one direct super class. This increases complexities and ambiguity in the relationship among classes. The problem is clearly visible if we consider what happens in function overriding.
There are some issues with inheritance, however. One big issue is that it doesn't always make sense for an object to inherit all the functionality of another kind of object. This is more of an issue with classical inheritance, since prototypal inheritance can be targeted to individual objects and not just classes.
Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly coupled. This means one cannot be used independent of each other.
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when there exist methods with the same signature in both the superclasses and subclass.
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.
Class fields do not participate in polymorphism game. The methods do.
So, when you access the field you go to one that is defined in base class because you object's type is Item
. When you call method you get the actual value because you invoke method using polymorphism.
Conclusion:
Fields are always private. If you want to access field write method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With