gpt4 book ai didi

java - 方法不重写或实现父类(super class)型中的方法 @override 编译错误

转载 作者:行者123 更新时间:2023-12-02 10:42:16 25 4
gpt4 key购买 nike

我收到错误方法没有重写或实现父类(super class)型@Override 中的方法。我想在打印一辆车后打印“无法更改汽车的容量”。我需要重写 setCapacity 来打印其他部分。我相信代码大部分是正确的,只是不确定为什么它没有正确覆盖 setCapacity 方法。最终输出为:

New capacity = 1600
Vehicle Info:
capacity = 1600cc
make = Mazda
Cannot change capacity of a car
Vehicle Info:
capacity = 1200cc
make = Holden
type = sedan
model = Barina

我的代码是:

class Vehicle {  // base class

public void setCapacity(int setCapacity) {
this.capacity = setCapacity;
System.out.println("New Capacity = " + setCapacity);
}

int capacity;
String make;

Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}

void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
}

class Car extends Vehicle {
public String type;
public String model;

public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake);
type = theType;
model = theModel;
}

@Override
public void print() {
super.print();
System.out.println(" type = " + type);
System.out.println(" model = " + model);

}

@Override
public void setCapacity() {
super.print();
System.out.println("Cannot change capacity of a car");
}
}

class Task3 {

public static void main (String[]args){
Car car1 = new Car (1200,"Holden","sedan","Barina" );
Vehicle v1 = new Vehicle (1500,"Mazda");
v1.setCapacity(1600);
v1.print();
car1.setCapacity(1600);
car1.print();
}
}

最佳答案

setCapacity() 的子方法和父方法签名不匹配。如果您想在子类中重写父类的方法,那么它必须具有相同的签名。

改变

public void setCapacity() { //... }

public void setCapacity(int setCapacity) { // ... }

Car 类中。

在您的代码中,您错过了参数setCapacity,因此编译器会提示。

关于java - 方法不重写或实现父类(super class)型中的方法 @override 编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52855550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com