Java中的防御者方法或虚拟方法是什么?
Java接口中的默认方法也称为防御者方法或虚拟方法。
防御者/虚拟方法是在接口中具有默认实现的方法。您可以使用默认关键字将防御者/虚拟方法定义为-
default void display() {
System.out.println("This is a default method");
}无需在实现类中实现这些防御者/虚拟方法,您可以直接调用它们。
如果您有一个由某些类实现的接口,并且想要添加一个新的方法,则为它。
然后,您需要在实现此接口的所有exiString类中实现此新添加的方法。这是很多工作。
要解决此问题,您可以为所有新实现的方法编写默认/防御程序/虚拟方法。
示例
以下Java示例演示了Java中默认方法的用法。
interface sampleInterface{
public void demo();
default void display() {
System.out.println("This is a default method");
}
}
public class DefaultMethodExample implements sampleInterface{
public void demo() {
System.out.println("This is the implementation of the demo method");
}
public static void main(String args[]) {
DefaultMethodExample obj = new DefaultMethodExample();
obj.demo();
obj.display();
}
}输出结果
This is the implementation of the demo method This is a default method
热门推荐
10 简短的小孩春节祝福语
11 喜得孙子祝福语简短独特
12 简短霸气的考试祝福语
13 周末思念祝福语大全简短
14 祝老婆生日祝福语简短
15 爱情祝福语大全 简短实际
16 祝福语大全简短6个
17 鼓掌祝福语简短10字
18 形容新年的祝福语简短