简体   繁体   中英

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.

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());
    }
}

Inner classes are ultimately meant to provide some utility to the outer class in terms of organization. The inner class is completely accessible to the outer class, because ultimately you really should never need to hide data from your own class. When the complexity of your code requires you to hide data behind getters and setters, you should be seriously considering the possibility of putting that class in its own file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM