Java没有方法的接口_我们可以在Java中编写没有任何方法的接口吗?

是的,您可以编写没有任何方法的接口。这些称为标记接口或标记接口。

标记接口,即通过实现这些接口不包含任何方法或字段,类相对于所实现的接口将表现出特殊的行为。

示例

考虑下面的示例,这里我们有一个名为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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值