java default关键字的作用是什么
Java中的default关键字有三种不同的用法,具体取决于其所在的上下文。
- 在switch语句中,default关键字表示默认情况。当switch语句中的表达式的值与任何一个case语句的值都不匹配时,程序将执行default语句块中的代码。
int day = 5;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// ...
default:
System.out.println("Other day");
}
- 在接口中,default关键字用于定义默认方法。默认方法在接口中有方法体的实现,默认方法可以被接口的实现类直接使用,而无需重写。
public interface MyInterface {
void doSomething();
default void doOtherThing() {
System.out.println("Do other thing");
}
}
public class MyClass implements MyInterface {
@Override
public void doSomething() {
System.out.println("Do something");
}
}
MyClass myObject = new MyClass();
myObject.doSomething(); // 输出:Do something
myObject.doOtherThing(); // 输出:Do other thing
- 在注解中,default关键字用于指定注解元素的默认值。在使用注解时,如果没有为注解元素提供值,那么将使用默认值。
public @interface MyAnnotation {
String value() default "Default value";
}
@MyAnnotation
public class MyClass {
// ...
}
MyClass myObject = new MyClass();
MyAnnotation annotation = myObject.getClass().getAnnotation(MyAnnotation.class);
System.out.println(annotation.value()); // 输出:Default value
总结:default关键字的作用取决于其上下文,可以表示默认情况、定义默认方法或指定注解元素的默认值。
相关问答