如何在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("汽车发行");
}
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());
}
}输出结果
汽车发行 取车
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语