Ido Traini
Ido Traini

Reputation: 83

Undestanding Java Inheritance: strange behaviour

I don't understand a strange behavior of class inheritance.

This is my parent class:

public class Cubetti implements Token{
   ...
    private int id=1;
   ...
    public Cubetti(int n) {
        numero = n;
    }
   ...
    public int getId() { return id; }
    public void setId( int idx) { id = idx; }
   ...
}

and this is the subclass:

public class RGC extends Cubetti{
    private int id=0;
   ...
    public RGC (int idx) { 
        super(0);
        id = idx; // STRANGE BEHAVIOUR !
    }
   ...
}

This is the test mainclass:

public static void main(String[] args) {

        RGC uno = new RGC(1);
        RGC due = new RGC(2);

        System.out.println(" uno Id is  " + uno.getId() + " due Id is" + due.getId());

 }

The output is

Uno Id is 1 and due Id is 1

but if I use in the tagged line on the RGC subclass:

....
// id = idx;
setId(idx);
....

The output is

Uno Id is 1 and due Id is 2

Why?

Upvotes: 1

Views: 97

Answers (2)

Ratul Sharker
Ratul Sharker

Reputation: 8011

In Java::
private properties are not inherited to the derived class. So the Cubetti's private property is not seen (directly accessible) in the scope of RGC's class. Cubetti's id property is only accessible through the outside world using the get() & set() methods (if these method are declared public).

In the 1st case where your output is following:
Uno Id is 1 and due Id is 1
The reason is that, the Cubetti's getId() & setId() methods are inherited to the RGC class as they are public method of Cubetti class. So whenever you call the get() method you get the value of the Cubetti's id value, which is set to 1. That is why you get the value 1 for both Uno & Due.

In the second case:
you place setId() in the RGC constructor. Here you basically set the id of the Cubetti's ID. Thus calling the getId() the id of the Cubetti is being returned.

Upvotes: 0

Eran
Eran

Reputation: 393791

You have an id variable in both the Cubetti super-class and RGC sub-class. Using the setter and getter updates/returns the id of the super-class, since those methods are defined in the super-class and are not overridden by the sub-class.

Calling id = idx in the sub-class constructor modifies the sub-class's variable, since the sub-class's variable hides the super-class's variable, and even if it didn't hide it, you wouldn't be able to access it from the sub-class, since it's private.

Upvotes: 3

Related Questions