Java中可以编写没有任何方法的接口吗?
是的,您可以编写没有任何方法的接口。这些被称为标记接口或标签接口。
标记接口,即它不包含任何方法或字段。通过实现这些接口,类将表现出关于所实现接口的特殊行为。
示例
考虑以下示例,这里我们有一个名为**Student**的类,它实现了标记接口**Cloneable**。在主方法中,我们尝试创建一个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
在这种情况下,Cloneable接口没有任何成员,您只需要实现它来标记或标记类,表明其对象是可克隆的。如果我们不实现此接口,则无法使用Object类的clone方法。
如果您仍然尝试,它会抛出**java.lang.CloneNotSupportedException**异常。
示例
在下面的Java程序中,我们尝试在不实现**Cloneable**接口的情况下使用Object类的**clone()**方法。
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)
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP