How to access the private variables of a class in its subclass?

前端 未结 28 2306
清歌不尽
清歌不尽 2020-12-17 09:46

This is a question I was asked in an interview: I have class A with private members and Class B extends A. I know private members of a class cannot be accessed, but the qu

28条回答
  •  失恋的感觉
    2020-12-17 10:25

    A nested class can access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.

    public class SuperClass
    {
        private int a = 10;
        public void makeInner()
        {
            SubClass in = new SubClass();
            in.inner();
        }
        class SubClass
        {
            public void inner()
            {
                System.out.println("Super a is " + a);
            }
        }
        public static void main(String[] args)
        {
            SuperClass.SubClass s = new SuperClass().new SubClass();
            s.inner();
        }
    }
    

提交回复
热议问题