Java中的空接口称为标记接口,即,通过实现这些接口,它不包含任何方法或字段,一类相对于所实现的接口将表现出特殊的行为。java.lang.Cloneable和java.io.Serializable是标记接口的示例。
请看以下示例,这里我们有一个名为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
在下面的Java程序中,Student类具有两个实例变量name和age,其中age被声明为瞬态。在另一个名为ExampleSerialize的类中,我们尝试对Student对象进行序列化和反灭菌,并显示其实例变量。由于年龄是不可见的(短暂的),因此仅显示名称值。
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Student implements Serializable{ private String name; private transient int age; public Student(String name, int age){ this.name = name; this.age = age; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public int getAge() { return this.age; } } public class ExampleSerialize { public static void main(String args[]) throws Exception{ Student std1 = new Student("Krishna", 30); FileOutputStream fos = new FileOutputStream("e:\\student.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(std1); FileInputStream fis = new FileInputStream("e:\\student.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Student std2 = (Student) ois.readObject(); System.out.println(std2.getName()); } }
输出结果
Krishna