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

查看:170
本文介绍了java - 为什么子类可以调用父类的私有构造方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

解决方案

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

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

这篇关于java - 为什么子类可以调用父类的私有构造方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆