开发者社区> 问答> 正文

为什么子类可以调用父类的私有构造方法

screenshot
screenshot
如上图,为什么子类可以调用父类的私有构造方法?

展开
收起
蛮大人123 2016-03-13 11:31:24 2895 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪
    public class UnSafeSequence {
        public class TestMath{
            private TestMath(){
                System.out.println("父类实例化");
            }
        }
        
        public class TestMath1 extends TestMath{
            public TestMath1(){
                System.out.println("子类实例化");
            }
        }
        
        /**
         * @param args
         */
        public static void main(String[] args) {
            System.out.println(new UnSafeSequence().new TestMath1());
            
        }
    }

    java6语言规范中关于private修饰符的描述,顶级类及内部类的定义

    6.6.1
    if the member or constructor is declared private, then 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.

    如果一个类的成员或构造器声明为private的,那么只有声明这个成员或构造器的顶级类才有权访问(当然声明这个成员和构造函数的类也是可以访问的)

    8.
    A top level class is a class that is not a nested class.
    A nested class is any class whose declaration occurs within the body of another class or interface. A top level class is a class that is not a nested class.
    顶级类不是一个嵌套类(内部类),嵌套类(内部类)是申明在其他类或接口中的类
    鉴于以上的规定描述,那么外部类中可以访问构造器标示为private的TestMath内部类。
    TestMath1同样是一个内部类,其继承了另一个内部类TestMath,因为一个内部类依赖外部类实例对象而存在,会隐式的关联一个外部类实例

    所以

     public class TestMath1 extends TestMath{
            public TestMath1(){
                System.out.println("子类实例化");
            }
        }

    可以写成

      public class TestMath1 extends UnSafeSequence.TestMath{
            public TestMath1(){
                UnSafeSequence.this.super();
                System.out.println("子类实例化");
            }
        }

    这样就可以解释一个内部类的子类为什么可以访问其父类的私有的构造函数了

    2019-07-17 19:02:19
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
建立联系方法之一 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载