java跨包访问内部类_java – 不能从另一个包的子类访问受保护的内部类

我在Java中有以下代码:

package a;

public classs ClassInOtherPackage{

protected void protectedMethod(){}

protected class protectedInnerClass {}

}

package b;

import a.*;

public class MyClass extends ClassInOtherPackage{

public MyClass(){

MyClass x = new MyClass();

x.protectedMethod(); //

//UPDATED: Declaration is ok

MyClass.protectedInnerClass y; //

//UPDATED: Only when instantiated is not allowed, why?

y = x.new protectedInnerClass(); //

}

}

请参阅Java文档:

“The protected modifier specifies that the member can only be accessed

within its own package (as with package-private) and, in addition, by

a subclass of its class in another package.”

为什么我不能实例化如上所示的内部受保护类?

解决方法:

8.8.9. Default Constructor

… if the class is declared protected, then the default constructor is implicitly given the access modifier protected (07001); …

所以隐式声明的构造函数是:

protected class protectedInnerClass {

protected protectedInnerClass(){

super();

}

}

您的代码将无法编译,因为构造函数不可访问.

标签:java,inner-classes,subclass

来源: https://codeday.me/bug/20190714/1460378.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值