如何在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 红包祝福语简短10字
18 周六早晨祝福语简短