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("汽车发行");
}
public void collectCar(Car c) {
System.out.println("取车");
}
public static void main(String args[]){
InterfaceSample obj = new InterfaceSample();
obj.lendCar(new CarRentalServices.Car());
obj.collectCar(new CarRentalServices.Car());
}
}输出结果
汽车发行 取车