【发布时间】:2016-12-06 22:25:00
【问题描述】:
我有 - Worker 接口。 每个工人都有能量。
public interface Worker {
int work();
double getEnergy();
}
和 - 实现 Worker 接口的初级工人类。 初级工人有100能量。
public class juniorWorker implements Worker {
public int work() {
return (int) getEnergy();
}
public double getEnergy() {
return 100;
}
}
还有 -efficientWork、powerWork 类,实现 Worker 接口。 高效工作将减少 20% 的能源。 powerWork 将提高 10% 的能量。
public class efficientWork implements Worker {
private Worker worker;
public efficientWork(Worker w) {
this.worker=w;
}
public int work() {
return (int) (worker.getEnergy()*getEnergy());
}
public double getEnergy() {
return 0.8;
}
}
public class PowerWork implements Worker {
private Worker worker;
public PowerWork(Worker w) {
this.worker=w;
}
public int work() {
return (int) (worker.getEnergy()*getEnergy());
}
public double getEnergy() {
return 1.1;
}
}
实际上,我正在尝试 int work() 将总结每个工人将花费的总 energy。 比如我的Demo课:
public class Demo {
public static void main(String[] args) {
Worker j= new efficientWork(new juniorWorker());
System.out.println(j.work());
}
}
这种情况正在运行 - 系统将打印 80。
但是这个例子,总是打印 0:
public class Demo {
public static void main(String[] args) {
Worker j= new efficientWork(new PowerWork(new juniorWorker()));
System.out.println(j.work());
}
}
帮助?我希望得到88! (110*0.8)
【问题讨论】:
-
你为什么将一个worker对象传递给所有实现worker的类?
-
我希望得到 88 个! (110*0.8)
-
@HovercraftFullOfEels 刚刚解释了一些。
-
只需使用调试器逐步执行
efficientWorker和PowerWork的work方法,您就会立即看到错误所在。总的来说:养成你的命名习惯。这些名称与 Java 中的“好”名称相去甚远。