簡體   English   中英

方法不會從父類型@override覆蓋或實現方法編譯錯誤

[英]method does not override or implement a method from a supertype @override compile error

我收到一個錯誤method does not override or implement a method from a supertype @Overridemethod 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();
   }
}

setCapacity()setCapacity()方法和父代方法簽名不匹配。 如果要覆蓋子類中父類的方法,則它必須具有相同的簽名。

更改

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

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

Car課上。

在您的代碼中,您錯過了參數setCapacity ,因此編譯器抱怨。

void setCapacity(int setCapacity)不被覆蓋。 void setCapacity()void setCapacity(int setCapacity)是兩種不同的方法。 因此,生成@Override批注的編譯錯誤。

關於術語,在這種情況下, setCapacity被認為是過載的。

在車輛類和汽車類中,createCapacity的簽名不同。 因此,存在編譯錯誤。 在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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM