0

我的电机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();
    }

}

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

4

2 回答 2

0

您的 main 方法实际上并没有创建diffPilot. 您应该在diffPilot.forward();.

你应该做

diffPilot = new CustomDifferentialPilot(...);

在调用之前在您的主要方法中.forward()

于 2013-01-29T20:53:16.610 回答
0

忘记传递super()给被覆盖的方法。

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

public void backward() {
    super.forward();
}
于 2013-01-30T10:03:29.917 回答