Java 中的防御方法或虚拟方法是什么?
Java 中的接口中的默认方法也称为防御方法或虚拟方法。
防御方法/虚拟方法是那些在接口中具有默认实现的方法。你可以使用 default 关键字定义防御方法/虚拟方法,如下所示 -
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
广告
数据结构
网络技术
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP