Having the same variable in both sub and superclasses

In this question, the output is given as Rose0. But when I look through the logic, I believe that the answer should be Rose100 instead of Rose0. How the compiler distinguishes I s in both classes. Since Rosea extends the _39 class, it also has a super i class. But on line 1, if I change super.i, then Im will get Rose100. How is that different?

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();
  }
}
+4
source share
2 answers

First of all, a variable iin a subclass will hide the variable in the superclass. Therefore, you need to write super.ito Roseaif you want to access _39.i.

Second: even if you call footo a superclass, the call will be executed for implementation in a subclass.

...

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

Rosea.foo i Rosea i, _39.i .

Java , .. , , . ( .)

:

+5

, . , Rosea::foo() i . , i , super.i.

+1

All Articles