user2445123
user2445123

Reputation:

Having a same variable in both sub and super classes

In this question the output gives as Rose0. But when I go through the logic I feel the answer must be Rose100 instead of Rose0. How does compiler differentiate the i s in both classes. Since Rosea extends _39 class it has the super class i as well. But in line 1 if I change super.i then Im getting Rose100. How this differs?

class _39 {
  int i;

  _39(){
    i=100;
    foo();
  }

  public void foo(){
    System.out.println("Flower"+i);}
  }
}

public class Rosea extends _39{

  int i=200;

  Rosea(){ 
      i=300;
  }

  public void foo(){
    System.out.println("Rose"+i);
  } //line 1

  public static void main(String[] args) {
    new Rosea();
  }
}

Upvotes: 4

Views: 73

Answers (2)

songyuanyao
songyuanyao

Reputation: 172914

The variables with same name in the derived class hide the ones in base class. So in function Rosea::foo(), the i of derived class will be used. As you wrote in your question, if you want to use i of base class, you must explicitly write super.i.

Upvotes: 1

aioobe
aioobe

Reputation: 420951

First of all, the variable i in the subclass will hide the variable in the super class. So you'll have to write super.i in Rosea if you want to access _39.i.

Second: Even if you call foo in the super class, the call will be made to the implementation in the subclass.

...

    _39() {
        i = 100;
        foo();     <--------------- this calls this
    }                                            |
                                                 |
...                                              |
                                                 |
public class Rosea extends _39 {                 |
    ...                                          |
    public void foo() {                  <-------'
        System.out.println("Rose" + i);
    }
    ...
}

And in the Rosea.foo i refers to Roseas version of i since _39.i is hidden.

All methods in Java are virtual, i.e. it's the runtime type of the object that determines which method is invoked. (Even if the call is made from within the super class.)

Further reading:

Upvotes: 5

Related Questions