我是客观编程的新手,我需要使用其他类的方法。 我有方法decreaseTemperature(int alpha);在java类中名为Reactor(它只是一个简单的命令alpha - = 1)它应该每fps降低1的温度....
Reactor reactor = new Reactor(); - 我不能用这个
public class Cooler extends AbstractActor{
private final Animation fanAnimation;
public Cooler(Reactor reactor){ //this must be like that
fanAnimation = new Animation("resources/images/fan.png", 32, 32, 200);
setAnimation(fanAnimation);
fanAnimation.setPingPong(true);
}
@Override
public void act(){
reactor.decreaseTemperature(1); //Here is a problem (this does not work)
}
}
答案 0 :(得分:2)
您的act()
方法无法访问reactor
实例变量。如果需要将其传递给Cooler
构造函数,则需要保存它以便类中的其他方法可以访问它。试试这个:
private final Animation fanAnimation;
private Reactor reactor;
public Cooler(Reactor reactor){ //this must be like that
this.reactor = reactor; // save the passed in parameter
fanAnimation = new Animation("resources/images/fan.png", 32, 32, 200);
setAnimation(fanAnimation);
fanAnimation.setPingPong(true);
}
@Override
public void act(){
reactor.decreaseTemperature(1); // this now refers to the private Reactor instance variable
}