Marco
Marco

Reputation: 499

Java nested class visibility rules

Is there a less cumbersome way to access field n of object other below?

public class NestedVisibility
{
    private int n = 42;

    public static class B extends NestedVisibility {
        public void foo(NestedVisibility guest) {
            super.n = 0; // OK
            guest.n = 0; // OK

            B other = new B();
            other.n = 0; // Compile-time error. Weird!
            ((NestedVisibility)other).n = 0; // OK
        }
    }
}

Isn't it odd that I have to do more work to access a private field of other than a private field of guest?

Upvotes: 0

Views: 161

Answers (2)

Thatalent
Thatalent

Reputation: 424

Private variables are not inherited by extending classes. You can access them through getters and setters that are inherited by the parent class.

This is your code rewritten to follow that:

public class NestedVisibility
{
    private int n = 42;

    public int getN(){
        return this.n;
    }

    public void setN(int n){
        this.n = n;
    }

    public static class B extends NestedVisibility {
        public void foo(NestedVisibility guest) {
            super.n = 0; // OK
            guest.n = 0; // OK

            B other = new B();
            other.setN(0);
            console.log(other.getN());
        }
    }
}

So basically class B does not have a field n but it's super does. This post has a lot more information on that, plus there's lots of random blogs in the interwebs about it.

You can access the private variable from the nested class though. As in, if you make an object whose type is NestedVisibility (not extend) then you can directly access it within a nested class like the following:

public class NestedVisibility
{
    private int n = 42;

    public static class B extends NestedVisibility {
        public void foo(NestedVisibility guest) {
            super.n = 0; // OK
            guest.n = 0; // OK

            NestedVisibility other = new NestedVisibility();
            other.n = 0; //OK
        }
    }
}

Hope this helps clear things up.

Upvotes: 1

MaxZoom
MaxZoom

Reputation: 7763

Private scope variables, are visible only to the class to which they belong.


If you expect the class to be extended and want to grant an access to the class variable, you should declare it with a protected scope.

public class NestedVisibility
{
  protected int n = 42;

  public static class B extends NestedVisibility {
    public void foo(NestedVisibility guest) {
      super.n = 0; // OK
      guest.n = 0; // OK

      B other = new B();
      other.n = 0; // now is OK
      ((NestedVisibility)other).n = 0; // OK
    }
  }
}

Upvotes: 0

Related Questions