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

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


一般来说,子类不可以调用父类的私有构造方法。
你这里这两个类都是同一个类的成员内部类,内部类可以自由地访问外部类的成员变量,即使是private的。所以一个成员内部类中可以访问另一个成员内部类(因为它可以看成是一个成员变量),被访问的成员内部类对访问它的成员内部类完全不设防。


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("子类实例化");
        }
    }

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


内部类本来就可以访问任意外部类的私有方法和字段,TestMath1继承的TestMath本身就是UnSafeSequence的内部类,所以TestMath1能够访问UnSafeSequence里定义的任何私有方法和字段包括了TestMath里的私有方法和字段。

如果你把TestMath单独定义在UnSafeSequence外面,那TestMath1就不能访问TestMath里的私有方法和字段了。

【热门文章】
【热门文章】