对象是java最基本的一个概念,对于对象的初始化小伙伴们了解吗?本篇文章就一起来看看。
对象初始化
类
//待实例化的类 public class Worker implements Cloneable, Serializable { private static final long serialVersionUID = 1 L; private String name; private Integer age; public Worker() { this.name = ""; this.age = 0; } public Worker(String name, Integer age) { this.name = name; this.age = age; } public void work() { System.out.println(name + "is working"); } public Worker clone() { Worker worker = null; try { return (Worker) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return worker; } }
方式一:
public static Worker createWorker() { System.out.println("直接使用new的方式,不使用参数"); return new Worker(); }
方式二:
public static Worker createWorker1() { Class clazz = null; Worker worker = null; try { clazz = Class.forName("com.code.loader.Worker"); worker = (Worker) clazz.newInstance(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } System.out.println("使用反射机制,不带参数的newInstance()方法"); return worker; }
方式三:
public static Worker createWorker4(String name, Integer age) { Worker person = new Worker(); person.setName(name); person.setAge(age); //序列化 OutputStream outputStream = new FileOutputStream("person.txt"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(person); outputStream.close(); objectOutputStream.close(); //反序列化 InputStream inputStream = new FileInputStream("person.txt"); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); return (Worker) objectInputStream.readObject(); }
以上就是本篇文章的所有内容,更多详细java常见问题及解决方法可以关注我们网站了解具体。
推荐阅读: