帮忙检查一下

来源:5-3 自由编程

cj啦啦啦啦

2019-11-25 15:53:22

package com.imooc.serializable;

import java.io.Serializable;

public class Product implements Serializable{
	private int id;
	private String name;
	private String type;
	private double price;
	public Product(int id, String name, String type, double price) {
		super();
		this.id = id;
		this.name = name;
		this.type = type;
		this.price = price;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return " [产品ID:" + id + "\n 产品名称:" + name + "\n 产品属性:" + type + "\n 产品价格:" + price + "]";
	}
	

}

package com.imooc.serializable;


import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.OutputStreamWriter;


public class Test {


public static void main(String[] args) {

Product p1=new Product(123,"iphone","telephone",4888);

Product p2=new Product(234,"ipad","computer",5088);

Product p3=new Product(345,"macbook","computer",10688);

Product p4=new Product(256,"iwatch","watch",4799);

System.out.println("apple系列产品信息");

try {

FileOutputStream fos=new FileOutputStream("product.txt");

ObjectOutputStream osw = new ObjectOutputStream(fos);

FileInputStream fis=new FileInputStream("product.txt");

ObjectInputStream ois=new ObjectInputStream(fis);

osw.writeObject(p1);

osw.writeObject(p2);

osw.writeObject(p3);

osw.writeObject(p4);

osw.flush();

try {

Product pr1=(Product) ois.readObject();

Product pr2=(Product) ois.readObject();

Product pr3=(Product) ois.readObject();

Product pr4=(Product) ois.readObject();

System.out.println(pr1);

System.out.println("\n"+pr2);

System.out.println("\n"+pr3);

System.out.println("\n"+pr4);

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

fos.close();

osw.close();

fis.close();

ois.close();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}


}


}


写回答

1回答

好帮手慕小尤

2019-11-25

同学你好,已实现练习,棒棒哒!不过有一个小建议,建议在Product类中创建无参构造。因如果定义带参构造但未定义无参构造,则带参构造会覆盖掉默认的无参构造,当使用无参构造方法创建对象时,会报找不到无参构造方法错误。

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

0

0 学习 · 11489 问题

查看课程