如何在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 城市祝福语简短10字
17 冬至婆婆的祝福语简短
18 直播生孩子祝福语简短