1、用途
在Java中,default
关键字有两个主要用途:用于接口的默认方法以及用于switch语句中的默认分支。
1. 接口中的默认方法
Java 8引入了接口的默认方法功能。通过在接口中使用default
关键字,接口可以为某些方法提供默认实现。这使得接口可以在不破坏现有实现的情况下向后兼容地添加新方法。
示例:
interface MyInterface {
// 默认方法
default void defaultMethod() {
System.out.println("This is a default method.");
}
// 抽象方法
void abstractMethod();
}
class MyClass implements MyInterface {
// 实现抽象方法
public void abstractMethod() {
System.out.println("Abstract method implementation.");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.defaultMethod(); // 调用默认方法
obj.abstractMethod(); // 调用抽象方法的实现
}
}
在上面的例子中,defaultMethod
是一个默认方法,它在接口MyInterface
中提供了一个默认实现。类MyClass
没有重写这个方法,但仍然可以通过实现接口直接使用它。
2. switch语句中的默认分支
default
关键字还用于switch
语句中,作为处理没有匹配值时的默认分支。它类似于else
在if-else
语句中的作用。
示例:
int number = 3;
switch (number) {
case 1:
System.out.println("Number is 1");
break;
case 2:
System.out.println("Number is 2");
break;
default:
System.out.println("Number is not 1 or 2");
break;
}
在这个例子中,如果number
的值不是1或2,则default
分支会被执行,输出 “Number is not 1 or 2”。
总结来说,default
关键字在Java中主要用于接口的默认方法和switch
语句中的默认分支。
2、接口的默认方法一定会被执行吗?
接口中的默认方法并不一定会被执行。是否执行取决于子类或实现类是否重写了该默认方法以及子类实例的调用情况。
以下是几种情况:
1. 实现类不重写默认方法
如果实现类没有重写接口的默认方法,那么调用这个方法时,默认方法将被执行。
示例:
interface MyInterface {
default void defaultMethod() {
System.out.println("This is the default method.");
}
}
class MyClass implements MyInterface {
// 没有重写默认方法
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.defaultMethod(); // 输出: This is the default method.
}
}
在这个例子中,MyClass
没有重写接口中的默认方法,所以调用defaultMethod()
时,执行的就是接口中的默认实现。
2. 实现类重写默认方法
如果实现类重写了接口的默认方法,那么调用这个方法时,执行的将是实现类中的重写版本。
示例:
interface MyInterface {
default void defaultMethod() {
System.out.println("This is the default method.");
}
}
class MyClass implements MyInterface {
// 重写默认方法
@Override
public void defaultMethod() {
System.out.println("This is the overridden method.");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.defaultMethod(); // 输出: This is the overridden method.
}
}
在这个例子中,MyClass
重写了defaultMethod()
,所以当调用defaultMethod()
时,执行的是重写的方法。
3. 实现类提供了多个接口,且多个接口具有相同的默认方法
如果一个类实现了多个接口,并且这些接口具有相同的默认方法名,则必须在实现类中重写该方法,否则编译会失败。这是为了避免方法冲突。
示例:
interface InterfaceA {
default void defaultMethod() {
System.out.println("Default method from InterfaceA");
}
}
interface InterfaceB {
default void defaultMethod() {
System.out.println("Default method from InterfaceB");
}
}
class MyClass implements InterfaceA, InterfaceB {
// 必须重写defaultMethod来解决冲突
@Override
public void defaultMethod() {
System.out.println("Overridden method to resolve conflict.");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.defaultMethod(); // 输出: Overridden method to resolve conflict.
}
}
在这个例子中,由于InterfaceA
和InterfaceB
都具有defaultMethod()
的默认实现,MyClass
必须重写这个方法以解决冲突。
总结
接口的默认方法是否被执行,取决于实现类是否重写了该方法以及在运行时如何调用它。如果实现类没有重写默认方法,并且调用了这个方法,那么默认方法才会被执行。