如何在 Java 中在介面內編寫類?


Java 允許在介面中定義類。如果介面的方法接受類作為引數,並且該類未使用在其他地方,則這種情況下我們可以在介面中定義類。

示例

在以下示例中,我們有一個名為 CarRentalServices 的介面,並且此介面有兩個方法,它們接受 Car 類的物件作為引數。在此介面中,我們有類 Car

 即時演示

interface CarRentalServices {
   void lendCar(Car c);
   void collectCar(Car c);
   public class Car{
      int carId;
      String carModel;
      int issueDate;
      int returnDate;
   }
}
public class InterfaceSample implements CarRentalServices {
   public void lendCar(Car c) {
      System.out.println("Car Issued");
   }
   public void collectCar(Car c) {
      System.out.println("Car Retrieved");
   }
   public static void main(String args[]){
      InterfaceSample obj = new InterfaceSample();
      obj.lendCar(new CarRentalServices.Car());
      obj.collectCar(new CarRentalServices.Car());
   }
}

輸出

Car Issued
Car Retrieved

更新於:29-Jun-2020

294 檢視

啟動您的 事業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.