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 爱生日祝福语简短独特