覆盖函数并在扩展类中调用其他函数

时间:2013-01-29 20:51:13

标签: java inheritance mindstorms

我的NXT2 2.0的马达是向后的,现在每次我运行命令forward()时,它都会向后滚动。我正在使用DifferentialPilot来移动我的机器人,因此想要覆盖DifferentialPilot类中的几个函数。

我从该类继承并用我的自定义覆盖所有构造函数。 然后我覆盖了forward(),现在应该调用backward(),反之亦然。

然而,现在我得到了例外,我无法说出原因。

这是覆盖的类:

package lejos.robotics.navigation;
import lejos.robotics.RegulatedMotor;

public class CustomDifferentialPilot extends DifferentialPilot {

    public CustomDifferentialPilot(final double wheelDiameter, final double trackWidth, final RegulatedMotor leftMotor,
            final RegulatedMotor rightMotor) {
        super(wheelDiameter, trackWidth, leftMotor, rightMotor);

    }

    public CustomDifferentialPilot(final double wheelDiameter, final double trackWidth, final RegulatedMotor leftMotor,
            final RegulatedMotor rightMotor, final boolean reverse) {
        super(wheelDiameter, trackWidth, leftMotor, rightMotor, reverse);
    }

    public CustomDifferentialPilot(double leftWheelDiameter, double rightWheelDiameter, double trackWidth,
            RegulatedMotor leftMotor, RegulatedMotor rightMotor, boolean reverse) {
        super(leftWheelDiameter, rightWheelDiameter, trackWidth, leftMotor, rightMotor, reverse);
    }

    public void forward() {
        backward();
    }

    public void backward() {
        forward();
    }

}

我的机器人示例代码:

import lejos.robotics.navigation.CustomDifferentialPilot;


public class DriveTest {

    private static CustomDifferentialPilot diffPilot;
    public static void main(String[] args) {
        diffPilot = new CustomDifferentialPilot(10, 20, Motor.A, Motor.B);
        diffPilot.forward();
    }

}

是否在超类中调用一个函数,在一个不允许覆盖的方法中的子类中?

2 个答案:

答案 0 :(得分:0)

您的main方法实际上并未创建diffPilot的实例。您应该在diffPilot.forward();获得NullPointerException。

你应该这样做

diffPilot = new CustomDifferentialPilot(...);
在调用.forward();

之前,在主方法中

答案 1 :(得分:0)

忘记将super()传递给重写的方法。

public void forward() {
    super.backward();
}

public void backward() {
    super.forward();
}