default 在java中的用法
时间: 2023-09-13 13:07:48 浏览: 55
在 Java 中,`default` 是一个关键字,主要用于接口中的默认方法(Default Method)。默认方法是在 Java 8 中引入的新特性,它允许在接口中定义具有默认实现的方法。
默认方法可以为接口提供一个默认的实现,从而避免在实现该接口的类中重复编写相同的代码。如果实现类没有实现该方法,则会使用默认实现。如果实现类重写了该方法,则会使用实现类中的实现。
下面是一个默认方法的示例:
```java
public interface MyInterface {
default void myMethod() {
System.out.println("This is a default method.");
}
}
public class MyClass implements MyInterface {
// 实现类可以选择覆盖默认方法
@Override
public void myMethod() {
System.out.println("This is a custom method.");
}
}
public class Main {
public static void main(String[] args) {
MyInterface obj = new MyClass();
obj.myMethod(); // 输出 "This is a custom method."
}
}
```
在上面的代码中,`MyInterface` 接口定义了一个默认方法 `myMethod()`,该方法会输出一条默认的消息。`MyClass` 类实现了该接口,并覆盖了默认方法的实现。在 `Main` 类中创建了一个 `MyClass` 对象,并调用了 `myMethod()` 方法,输出了重写后的消息。