4

If I have a class with two static nested classes, is there any way to restrict access of private static fields in one class from the other? Example:

public class Outer {

  private static class Inner1 {

    private static int privateInner1 = 0;

    private Inner1() {
        System.out.println(privateInner1 + ", " + Inner2.privateInner2); // prints "0, 1"
    }
  }

  private static class Inner2 {
    private static int privateInner2 = 1;
  }

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

Not that I actually have a use case for this in mind, I'm just curios.

Thanks!

EvenLisle
  • 4,672
  • 3
  • 24
  • 47
  • Please visit this answer for more clarity [enter link description here](http://stackoverflow.com/questions/7279887/what-is-the-use-of-a-private-static-variable-in-java) – Munish Chouhan Feb 16 '17 at 06:23
  • @Munish I wasn't asking what the purpose of a private static variable was – EvenLisle Feb 17 '17 at 10:13

3 Answers3

3

From http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6.1

A private class member or constructor is accessible only within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

You can't restrict access to the inner classes from the outer class because members, whether public or private, of inner classes can be accessed by outer classes. And in this scenario, the main method is part of Outer, so it will be able to access the members of both Inner1 and Inner2. The closest you can get to your objective is by creating an instance of an interface inside the outer class and define member variables there. These member variables will not be accessible to the outer class. Here's an example,

private interface Example{
    void doSomething();
}
private Example Inner3 = new Example(){
    private int privateInner3 = 2;
    public void doSomething(){
        System.out.println(privateInner3);
    }
}

Now in your main method, you won't be able to access Inner3.privateInner3, but you can call Inner3.doSomething().

Chris Gong
  • 8,031
  • 4
  • 30
  • 51
2

No way, the least access you can give is private(which you already gave) and since you are trying to access them in the same class, there is no way you can stop them accessing, after all they are members belong to the same family.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

You can't. Inner classes are intended to be used when some functionality of the outer class is clearer when it is extracted in another class, but it is still tightly coupled with the outer class. So basically you should be using the inner class within the outer class to have better code separation.

Sorin
  • 61
  • 6