0

I'm having some trouble understanding how this code exactly works.

public class Outer {

    private int num = 0;

    public void setNum(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }

    public Outer inner() {
        return new Inner();
    }

    private class Inner extends Outer {

        public int getNum() {
            // do something extra
            return super.num; // changing to 'this.num' throws an error
        }
    }
}

Running

    Outer o = new Outer();
    Outer i = o.inner();
    o.setNum(4);
    i.setNum(5);
    System.out.println(i.getNum());

correctly outputs 5, but if I change super.num to this.num I get an error saying The field Outer.num is not visible. Of course, if i set num to public the code does work. I just don't understand why it runs with super, but not with this.

Brett Lane
  • 101
  • 1

1 Answers1

0

In Java private variables of base classes are not visible any other class, not even for a derived class. (use protected instead)

I don't exactly know, but I suggest, that calling super, your class behaves like if it was the base class itself. Maybe a a java expert could check my suggestion.

p0kR
  • 80
  • 1
  • 12
  • That is not exactly it. The real answer is mentioned in the link I posted below this question – Tim Apr 04 '17 at 13:28