在Java中,default
是一个关键字,用于在接口中定义默认方法。Java 8引入了默认方法的概念,它允许在接口中提供方法的默认实现,而不需要实现类去实现这些方法。这样可以向现有的接口添加新的方法,而不会破坏实现该接口的现有类。
interface Vehicle {
// 默认方法
default void start() {
System.out.println("Vehicle is starting...");
}
// 抽象方法
void accelerate();
}
class Car implements Vehicle {
// 实现抽象方法
@Override
public void accelerate() {
System.out.println("Car is accelerating...");
}
}
class Motorcycle implements Vehicle {
// 实现抽象方法
@Override
public void accelerate() {
System.out.println("Motorcycle is accelerating...");
}
// 重写默认方法
@Override
public void start() {
System.out.println("Motorcycle is starting...");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.start(); // Output: Vehicle is starting...
car.accelerate(); // Output: Car is accelerating...
Motorcycle motorcycle = new Motorcycle();
motorcycle.start(); // Output: Motorcycle is starting...
motorcycle.accelerate(); // Output: Motorcycle is accelerating...
}
}