Search code examples
javastaticstatic-methodslego-mindstormslejos-nxj

Why do static classes crash my robot?


I have made the static class below so any class may access any of my lejos robot's sensor methods without me having to make an instance for each class.

However whenever I call a method such as StandardRobot.motorA.setPower(100) my robot crashes. When I use exactly the same class and make a local instance of it this works fine. Why is this? Both times my code compiles fine and fails at runtime.

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);
    }
}

Solution

  • You're trying to create a utility class, but your variable initialization takes place in a constructor.

    Constructors are only called when an instance is... constructed (via new).

    You need to initialize the static properties statically, either in a static initialization block, or as they're declared.

    // 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.
    }