方法不会从父类型@override编译错误中覆盖或实现方法

时间:2018-10-17 13:03:30

标签: java override

我遇到错误method does not override or implement a method from a supertype @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();
   }
}

3 个答案:

答案 0 :(得分:1)

setCapacity()的子代和父代方法签名不匹配。如果要覆盖子类中父类的方法,则它必须具有相同的签名。

更改

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

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

Car类中。

在您的代码中,您错过了参数setCapacity,因此编译器抱怨。

答案 1 :(得分:0)

void setCapacity(int setCapacity)不会被覆盖。 void setCapacity()void setCapacity(int setCapacity)是两种不同的方法。因此会生成@Override注释编译错误。

关于术语,在这种情况下,setCapacity被认为是超载的。

答案 2 :(得分:0)

createCapacity的签名在Vehicle和Car类中是不同的。因此,存在编译错误。在Vehicle类中,您有一个参数setCapacity,但在Car类中,该方法的参数列表为空。因此,无法覆盖。

@Override
public void setCapacity(   int capacity   ) { --> **adding this argument here will fix the issue.**
    super.print();
    System.out.println("Cannot change capacity of a car");
}

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