我的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();
}
}
是否在超类中调用一个函数,在一个不允许覆盖的方法中的子类中?
答案 0 :(得分:0)
您的main方法实际上并未创建diffPilot
的实例。您应该在diffPilot.forward();
获得NullPointerException。
你应该这样做
diffPilot = new CustomDifferentialPilot(...);
在调用.forward()
; 之前,在主方法中
答案 1 :(得分:0)
忘记将super()
传递给重写的方法。
public void forward() {
super.backward();
}
public void backward() {
super.forward();
}