继承时无法访问受保护的内部类 [英] Can't access protected inner class while inheriting
问题描述
阅读思考Java我坚持参加ex:6 of Inner Classes章节。
Reading through "Thinking in Java" i stuck in ex:6 of Inner Classes chapter.
练习6:(2)在自己的包中创建一个至少包含一个方法的接口。在单独的包中创建
类。添加一个实现该接口的受保护内部类。在
第三个包中,继承自您的类,并在方法内返回
protected内部类的对象,在返回期间向上转换为接口。
Exercise 6: (2) Create an interface with at least one method, in its own package. Create a class in a separate package. Add a protected inner class that implements the interface. In a third package, inherit from your class and, inside a method, return an object of the protected inner class, upcasting to the interface during the return.
这是我的代码:
interface
interface
package intfpack;
public interface IOne{
void f();
}
COne.java
具有实现接口的受保护内部类的类
COne.java
Class with protected inner class that implements the interface
package classpack;
import intfpack.*;
public class COne{
protected class Inner implements IOne{
public void f(){System.out.println("Inner class of COne");}
}
}
CTwo.java
继承自受保护内部类的类
CTwo.java
Inheriting from class with protected inner class
package thirdpack;
import classpack.*;
import intfpack.*;
public class CTwo extends COne{
public IOne getInner(){
IOne io = new Inner();
return io;
}
public static void main(String[] args){
CTwo ct = new CTwo();
ct.getInner();
}
}
Copmiler说下一个:
Copmiler says next:
javac CTwo.java
CTwo.java:9: Inner() has protected access in classpack.COne.Inner
IOne io = new Inner();
^
1 error
但书中说我可以访问受保护的内部派生类中的类。错误在哪里?
But the book says that i can access protected inner classes in derived class. Where is mistake?
推荐答案
错误消息是抱怨受保护的构造函数,而不是类。但是您没有在发布的代码中明确定义构造函数。在这种情况下,根据JLS ,默认构造函数将受到保护(与类相同)。
The error message is complaining about the constructor being protected, not the class. But you haven't explicitly defined a constructor in the code you posted. In this case, according to the JLS, the default constructor will be protected (the same as the class).
这篇关于继承时无法访问受保护的内部类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!