为什么静态类会使我的机器人崩溃?

时间:2011-10-25 06:02:23

标签: java static static-methods lego lejos-nxj

我已经在下面创建了静态类,所以任何类都可以访问我的lejos机器人的传感器方法,而不必为每个类创建一个实例。

然而,每当我调用诸如StandardRobot.motorA.setPower(100)之类的方法时,我的机器人就会崩溃。当我使用完全相同的类并生成它的本地实例时,这很好。为什么是这样?两次我的代码编译都很好并且在运行时失败。

import lejos.nxt.*;

public class StandardRobot {

    public static ColorSensor colourSensor;
    public static TouchSensor touchSensor;
    public static UltrasonicSensor ultrasonicSensor;
    public static NXTMotor motorA, motorB;

    public StandardRobot() {
        // instantiate sensors
        ultrasonicSensor = new UltrasonicSensor(SensorPort.S1);
        colourSensor = new ColorSensor(SensorPort.S2);
        touchSensor = new TouchSensor(SensorPort.S4);

        //instantiate motors
        motorA = new NXTMotor(MotorPort.A);
        motorB = new NXTMotor(MotorPort.B);
    }
}

4 个答案:

答案 0 :(得分:4)

您正在尝试创建实用程序类,但您的变量初始化发生在构造函数中。

构造函数仅在构造实例时被调用(通过new)。

您需要静态初始化静态属性,无论是在静态初始化块中,还是在声明它们时。

// Initialize static properties as they're declared.
public static ColorSensor colourSensor = new ColorSensor(SensorPort.S2);

// Or initialize in a static initialization block to do them all at once.
public static TouchSensor touchSensor;
// ... and the others.
static {
    touchSensor = new TouchSensor(SensorPort.S4);
    // ... and the others.
}

答案 1 :(得分:2)

因为当你没有调用构造函数StandardRobot时,你没有实例化motorA,motorB,ultrasonicSensor等,所以它们默认为null,导致运行时出现NullPointerExceptions。您可以将所有这些字段设为实例变量,也可以考虑使用静态初始化块,即

   static {
 // instantiate sensors
    ultrasonicSensor = new UltrasonicSensor(SensorPort.S1);
    colourSensor = new ColorSensor(SensorPort.S2);
    touchSensor = new TouchSensor(SensorPort.S4);

    //instantiate motors
    motorA = new NXTMotor(MotorPort.A);
    motorB = new NXTMotor(MotorPort.B);
}

答案 2 :(得分:2)

静态变量是为类定义的,而不是为实例定义的。您定义的构造函数是为实例调用的,而不是类。结果,您的变量可能未初始化。

在相关节点上:使变量保持静态的想法不是很好。你只限于拥有一个机器人,因为所有机器人都会分享状态。

答案 3 :(得分:0)

用静态部分替换你的构造函数:

static {
        // instantiate sensors
        ultrasonicSensor = new UltrasonicSensor(SensorPort.S1);
        colourSensor = new ColorSensor(SensorPort.S2);
        touchSensor = new TouchSensor(SensorPort.S4);

        //instantiate motors
        motorA = new NXTMotor(MotorPort.A);
        motorB = new NXTMotor(MotorPort.B);
}
相关问题