是的,您可以编写没有任何方法的接口。这些称为标记接口或标记接口。
标记接口,即通过实现这些接口不包含任何方法或字段,类相对于所实现的接口将表现出特殊的行为。
考虑下面的示例,这里我们有一个名为Student的类,该类实现了标记接口Cloneable。在main方法中,我们尝试创建Student类的对象,并使用clone()方法对其进行克隆。
import java.util.Scanner; public class Student implements Cloneable { int age; String name; public Student (String name, int age){ this.age = age; this.name = name; } public void display() { System.out.println("Name of the student is: "+name); System.out.println("Age of the student is: "+age); } public static void main (String args[]) throws CloneNotSupportedException { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.next(); System.out.println("Enter your age: "); int age = sc.nextInt(); Student obj = new Student(name, age); Student obj2 = (Student) obj.clone(); obj2.display(); } }
输出结果
Enter your name: Krishna Enter your age: 29 Name of the student is: Krishna Age of the student is: 29
在这种情况下,可克隆接口没有任何成员,您只需要实现它即可标记或标记表示其对象可克隆的类。如果我们不实现此接口,则不能使用Object类的clone方法。
如果仍然尝试,它将抛出java.lang.CloneNotSupportedException异常。
在下面的Java程序中,我们尝试使用Object类的clone()方法而不实现Cloneable接口。
import java.util.Scanner; public class Student{ int age; String name; public Student (String name, int age){ this.age = age; this.name = name; } public void display() { System.out.println("Name of the student is: "+name); System.out.println("Age of the student is: "+age); } public static void main (String args[]) throws CloneNotSupportedException { Student obj = new Student("Krishna", 29); Student obj2 = (Student) obj.clone(); obj2.display(); } }
该程序已成功编译,但是在执行时会引发运行时异常,如下所示:
输出结果
Exception in thread "main" java.lang.CloneNotSupportedException: Student at java.base/java.lang.Object.clone(Native Method) at Student.main(Student.java:15)