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

前端 未结 28 2378
清歌不尽
清歌不尽 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:20

    From JLS §8.3. Field Declarations:

    A private field of a superclass might be accessible to a subclass - for example, if both classes are members of the same class. Nevertheless, a private field is never inherited by a subclass.

    I write the example code:

    public class Outer
    {
        class InnerA
        {
            private String text;
        }
        class InnerB extends InnerA
        {
            public void setText(String text)
            {
                InnerA innerA = this;
                innerA.text = text;
            }
            public String getText()
            {
                return ((InnerA) this).text;
            }
        }
        public static void main(String[] args)
        {
            final InnerB innerB = new Outer().new InnerB();
            innerB.setText("hello world");
            System.out.println(innerB.getText());
        }
    }
    

    The explanation of the accessibility of InnerA.text is here JLS §6.6.1. Determining Accessibility:

    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 class (§7.6) that encloses the declaration of the member or constructor.

提交回复
热议问题