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 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志