Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inheritance issue

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.

like image 978
santosh-patil Avatar asked Aug 02 '11 07:08

santosh-patil


People also ask

What are the problems of inheritance in Java?

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.

What are the problems of inheritance?

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.

What is the 1 disadvantages of inheritance?

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.

Why is multiple inheritance a problem?

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.


2 Answers

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.

like image 146
Sanjay T. Sharma Avatar answered Oct 15 '22 16:10

Sanjay T. Sharma


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.

like image 36
AlexR Avatar answered Oct 15 '22 17:10

AlexR