【发布时间】:2015-08-25 14:52:24
【问题描述】:
我想从 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();
}
那么,有一个实现接口的内部类的类:
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 类的原因。我是不是误会了什么?
【问题讨论】:
标签: java inheritance inner-classes