本文通过代码示例介绍如何在 Java 中使用 default 关键字。
基本上,有 3 个地方可以使用 Java 中的 default 关键字:
在 switch case 语句中指定默认值
在 Java 注解中声明默认值
在接口中声明默认方法
下面看看使用 default 关键字的实例代码。
在下面的方法中,将 default 关键字用在 switch case 语句种用于返回默认值:
public static int getDaysOfMonth(int month) {
switch (month) {
case 2:
return 28;
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
在以下示例中,default 关键字用于为自定义注解类中的方法声明默认值:
public @interface Editable {
boolean value() default false;
String name() default "Untitled";
}
最后,default 关键字用于在接口中声明默认方法。 例如:
public interface Animal {
public void eat();
public void move();
public default void sleep() {
// implementation goes here...
}
}