如何在 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("Car Issued");
}
public void collectCar(Car c) {
System.out.println("Car Retrieved");
}
public static void main(String args[]){
InterfaceSample obj = new InterfaceSample();
obj.lendCar(new CarRentalServices.Car());
obj.collectCar(new CarRentalServices.Car());
}
}输出
Car Issued Car Retrieved
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP