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 对司机的祝福语简短