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
.