java 父类私有成员_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("子类实例化");

}

}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值