老师帮忙看下写在同一个类中有什么隐患或者建议
来源:5-3 自由编程
KLovei
2020-05-03 10:18:51
package com.imooc.file; 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.Serializable; import java.util.ArrayList; import java.util.List; public class Product implements Serializable { private String id; private String name; private String categories; private double price; public Product() { } public Product(String id, String name, String categories, double price) { this.setId(id); this.setName(name); this.setCategories(categories); this.setPrice(price); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCategories() { return categories; } public void setCategories(String categories) { this.categories = categories; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public String toString() { return "产品ID:" + id + "\n产品名称:" + name + "\n产品属性:" + categories + "\n产品价格:" + price + "元"; } public static void main(String[] args) { Product iphone = new Product("123", "iphone", "telephone", 4888); Product ipad = new Product("234", "ipad", "computer", 5088); Product macbook = new Product("345", "macbook", "computer", 10688); Product iwatch = new Product("256", "iwatch", "watch", 4799); try { ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Product.txt")); ObjectInputStream oin = new ObjectInputStream(new FileInputStream("Product.txt")); List<Product> list = new ArrayList<>(); list.add(iphone); list.add(ipad); list.add(macbook); list.add(iwatch); for (Product product : list) { out.writeObject(product); } try { for (int i = 0; i < list.size(); i++) { Product product = (Product) oin.readObject(); System.out.println(product + "\n"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } oin.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
如题
1回答
同学你好,当前的代码写在一个类中是没有问题的,但随着我们代码的业务逻辑逐渐变多,代码如果都在到一个类中书写和查看起来都很不方便,建议同学将代码分成不同的类来书写,这是良好的编程习惯。同学应该从现在就开始跟着老师的思路养成这种好的编程习惯,对以后开发工作是有很大帮助的。
如果我的回答解决了你的疑惑,请采纳!祝学习愉快~
相似问题