Ihor Ihor - 1 day ago 7
Java Question

Java: Access level of Inner classes

I was about to create a class inside another class

public class Sq {
class Inner {
private int a; //no getters setters
//a is private
private Inner (int a1) {
this.a = a1;
}
}
public static void main(String[] args) {
Sq outter = new Sq();
Inner d = outter.new Inner(3);
System.out.println("Private a = " + d.a);
}
}


It works.. so that i can get access to inner's private fields, also i've added Inner2 class and tried to change "a" from the Inner2 and it also worked :/

So looks like private in the inner class is not so private, looks like it's public within the whole class.

Answer

Nested classes are public for the outer class and private for all the others classes...

Some reference: Nested Classes

Declaring private the nested/inner class does not change the visibility to the outer class itself, just think the nested class (private or not) as a variable/method of the outer class.

public class Sq {
    public int publicNumber = 0;
    private int number = 0;
    private class Inner { ... }
}

EDIT

From the inner class you can also call some variable/method of the outer class and otherwise without problem

public class Sq {

    private int number = 0;

    class Inner {
        private int a;

        private Inner(int a1) {
            this.a = a1;
            number++;
        }

        private String getOuterClassString()
        {
            return getOuterString();
        }

        private String getPrivateString()
        {
            return "privateString";
        }

        public String getPublicString()
        {
            return "publicString";
        }
    }

    private String getOuterString()
    {
        return "outerString";
    }

    public static void main(String[] args) {
        Sq outter = new Sq();
        Inner d = outter.new Inner(3);
        System.out.println("Number = " + outter.number);
        System.out.println("Private a = " + d.a);
        System.out.println("Number = " + outter.number);

        System.out.println(d.getPrivateString());
        System.out.println(d.getPublicString());
        System.out.println(d.getOuterClassString());
    }
}
Comments