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