按照实体类创建规范创建图书类Book,包含四个属性(编号、书名、作者、价格)、无参构造器、有参构造器、重写toString方法,并在测试类中创建一个Book对象并将该对象存储到文件中(序列化)代码
时间: 2023-04-06 07:01:47 浏览: 101
以下是示例代码:
```
import java.io.*;
class Book implements Serializable {
private int id;
private String name;
private String author;
private double price;
public Book() {}
public Book(int id, String name, String author, double price) {
this.id = id;
this.name = name;
this.author = author;
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
", price=" + price +
'}';
}
}
public class Main {
public static void main(String[] args) {
Book book = new Book(1, "Java编程思想", "Bruce Eckel", 99.0);
try {
FileOutputStream fos = new FileOutputStream("book.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(book);
oos.close();
fos.close();
System.out.println("Book object has been serialized");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
注意:这里的代码只是示例,实际开发中需要根据具体需求进行修改和完善。
阅读全文