如何在 Java 中在接口内定义类?
java 8object oriented programmingprogramming
在 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