如何在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 爱生日祝福语简短独特