如何在 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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP