简体   繁体   中英

Private access modifier for methods in nested classes

Please consider the following code snippet.

public class HelloWorld{

    private static class InnerA{
        private int _a;

        private InnerA( int a ){
            _a = a;
        }

        private int getA(){
            return _a;
        }

    }

    private static class InnerB{
        private InnerB(){
            InnerA inner_a = new InnerA( 1 ); //isn't the constructor of InnerA private??
            System.out.println( inner_a.getA() ); //isn't getA() a private function of InnerA??
        }

    }
    public static void main(String []args){
       InnerB b = new InnerB();
    }
}

My questions are:

  1. InnerA 's constructor is marked as private, but why is it called successfully from inside InnerB 's constructor?

  2. Why can getA() , which is a private method of InnerA , be called from inside InnerB ? I thought marking the method as private would prevent it from being used outside of InnerA ?

From the language spec :

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level type (§7.6) that encloses the declaration of the member or constructor.

Things inside the same top-level class are always accessible.

Nested static classes have access to all members of its enclosing class, including private members.

They do not get access to instance members, public or private, of its enclosing instance. However, if you pass a method of a static nested class an instance of the enclosing class, the nested class would be able to access all members of the enclosing class, regardless of their access level.

Thedocumentation says:

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.

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