Java - Marker Interface
Interface with no fields or methods i.e. empty interface. Examples of marker interface are Serializable, Cloneable and Remote interface. All these interfaces are empty interfaces.
public interface Cloneable{
//nothing here
}
Cloneable interface
package oopsconcept;
public class Car implements Cloneable {
String carName;
int mileage;
// constructor of car class
public Car(String name, int mil) {
this.carName = name;
this.mileage = mil;
}
// Overriding clone() method by simply calling Object class clone() method.
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
Car c = new Car("Honda Amaze", 25);
// cloning 'c' and holding new cloned object reference in d
// down-casting as clone() return type is Object
Car d = (Car) c.clone();
System.out.println(d.carName);
System.out.println(d.mileage);
}
}
领英推荐
Output:
Honda Amaze
25
Serializable interface :
package oopsconcept;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class CarSerializable implements Serializable {
String carName;
int mileage;
// constructor of car class
public CarSerializable(String name, int mil) {
this.carName = name;
this.mileage = mil;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
CarSerializable c = new CarSerializable("Honda Amaze", 25);
// Serilaizing 'c'
File file = new File("person.txt");
FileOutputStream fo = new FileOutputStream(file);
ObjectOutputStream ob = new ObjectOutputStream(fo);
ob.writeObject(c);
System.out.println("File path: " + file.getAbsolutePath());
// Deserializing 'c'
FileInputStream fi = new FileInputStream("file.txt");
ObjectInput ob1 = new ObjectInputStream(fi);
// down-casting object
CarSerializable d = (CarSerializable) ob1.readObject();
System.out.println(d.carName + ":" + d.mileage);
// Close the streams
ob.close();
ob1.close();
}}
Output:
File path: D:\Selenium\Java Interview Question\person.txt
Honda Amaze:25
Remote interface :