(Java Programming)
Question 5:
Create a boat class with at least two properties. Write methods to archive the objects of boat type to disk and then reads and print the attributes.
Expert Answer
import java.io.*;
class Boat implements Serializable {
private String name;
private int weight;
public Boat() {
name = “”;
weight = 0;
}
public Boat(String name, int wt) {
this.name = name;
this.weight = wt;
}
public String getName() {
return name;
}
public int getWeight() {
return weight;
}
}
public class DemoSer {
public static void main(String[] args) {
try {
Boat b1 = new Boat(“name1”, 50);
// write object to a file
FileOutputStream fos = new FileOutputStream(“boat.ser”);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(b1);
os.close();
// read object from file
FileInputStream fis = new FileInputStream(“boat.ser”);
ObjectInputStream os1 = new ObjectInputStream(fis);
Boat obj = (Boat) os1.readObject();
os1.close();
System.out.println(“Name:” + obj.getName() + “, Weight:” + obj.getWeight());
} catch (Exception e) {
e.printStackTrace();
}
}
}