我想根据 Bruce Eckel 的 TIJ 对内部类进行以下练习:
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.
这是我的实现:
首先是界面:
package workers;
public interface Employable {
void work();
}
然后,一个带有实现该接口(interface)的内部类的类:
package second;
import workers.Employable;
public class WorkersClass {
protected class Worker implements Employable {
@Override
public void work() {
System.out.println("Hello, I'm a worker!");
}
}
}
最后是继承类:
package third;
import second.WorkersClass;
import workers.Employable;
public class Third extends WorkersClass {
Employable getWorker() {
return new Worker();//the line is reported to be incorrect
}
}
IDEA 在 getWorker
中用 Worker()
下划线,并建议将 Worker
类设为 public
。但为什么?它受到保护,这就是 WorkersClass
的后继者可以在其方法中实例化 Worker
类的原因。我是不是误解了什么?
最佳答案
问题不全在于访问说明符。
当您不在类中提供任何构造函数时,编译器会自动为您插入一个默认的无参数构造函数
在这种情况下,情况并非如此。因为编译的内部类没有获得默认构造函数,因为它被编译为 outer$inner
并且对于 inner
,编译器没有提供默认构造函数。
手动提供默认的 no org constructor
并查看魔术 :)
package second;
import workers.Employable;
public class WorkersClass {
protected class Worker implements Employable {
public Worker() {
// TODO Auto-generated constructor stub
}
@Override
public void work() {
System.out.println("Hello, I'm a worker!");
}
}
}
关于java - 实例化一个使用 protected 访问说明符继承的内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32207302/