我按照下面的UML来创建从引擎类调用委托方法的类,但是当我厌倦了创建法拉利类的对象并将其传递给引擎类型时,即{{1 }}。
我收到错误CombustionEngine
。
我从中收集到CombustionEngine cannot be resolved to a variable
对象无法看到从enzo
界面扩展的CombustionEngine
类。
任何人都可以看到我在层次结构的实现方面出了什么问题吗?
从Engine
扩展的CombustionEngine
课程:
Engine interface
public class CombustionEngine implements Engine {
//instance variables
private int speed;
public CombustionEngine(int speed) {
super();
this.speed = speed;
}
public CombustionEngine() {
super();
// TODO Auto-generated constructor stub
}
public void setSpeed(int speed) {
this.speed = speed;
}
@Override
public void stop() {
// TODO Auto-generated method stub
System.out.println("Combustion engine Stopped:");
}
@Override
public void start() {
// TODO Auto-generated method stub
System.out.println("Combustion engine Startedd:");
}
@Override
public void throttle(int power) {
// TODO Auto-generated method stub
speed += power;
}
@Override
public int getSpeed() {
// TODO Auto-generated method stub
return speed;
}
}
界面:
Engine
public interface Engine {
void stop();
void start();
void throttle(int power);
int getSpeed();
}
上课:
PowerVehicle
public class PoweredVehicle {
Engine engine;
public PoweredVehicle(Engine engine) {
super();
this.engine = engine;
}
public Engine getEngine() {
return engine;
}
public void Drive(){
System.out.println("Generic Driving");
}
public void setEngine(Engine engine) {
this.engine = engine;
}
public void stop() {
engine.stop();
}
public void start() {
engine.start();
}
public void throttle(int power) {
engine.throttle(power);
}
public int getSpeed() {
return engine.getSpeed();
}
}
类:
Ferrari
最后在public class Ferrari extends PoweredVehicle {
public Ferrari(Engine engine) {
super(engine);
// TODO Auto-generated constructor stub
}
Ferrari f = new Ferrari(engine);
@Override
public void Drive() {
// TODO Auto-generated method stub
super.Drive();
System.out.println("Ferrari driving...");
}
}
课程中,我尝试创建Runner
Ferrari
答案 0 :(得分:2)
Ferrari enzo = new Ferrari(CombustionEngine);
您的Ferrari
课程需要 Engine
类型的实例。 CombusionEngine
本身毫无意义。它是一个在内存中没有任何内容的名称。您需要先创建CombustionEngine
,然后将其传入。有点像......
CombustionEngine engine = new CombustionEngine(100); // Or whatever your speed is.
Ferrari enzo = new Ferrari(engine);
显然可以变成匿名对象..
Ferrari enzo = new Ferrari(new CombustionEngine(100));
答案 1 :(得分:1)
为什么要在Ferrari
类中创建Ferrari
的实例?
public class Ferrari extends PoweredVehicle
{
public Ferrari(Engine engine) {
super(engine);
}
Ferrari f = new Ferrari(engine); // Why would you do this here?
@Override
public void Drive() {
super.Drive();
System.out.println("Ferrari driving...");
}
}
在创建Ferrari
对象
public static void main(String[] args)
{
int someSpeed = 99;
Ferrari enzo = new Ferrari(new CombustionEngine(someSpeed));
}
在这里,您正在实现一个接口,因此不需要super()
public class CombustionEngine implements Engine
{
//instance variables
private int speed;
public CombustionEngine(int speed)
{
//super();
this.speed = speed;
}
....
}