一、创建对象的四种方法:
a. new语句;
b. 利用反射,调用描述类的Class对象的newInstance()实例方法;
c. 调用对象的clone();
d. 反序列化;
其中new 和 newInstance()会调用类的构造方法,而clone()和反序列化不会;
Cloneable接口:
Cloneable接口里没有定义方法,仅用于标记对象,clone()方法是Object类里面的方法,是一个protected native方法;
如果对象实现Cloneable接口的话,需要覆盖clone方法;
浅拷贝:只复制基本类型;
public class Person implements Cloneable{ private int age ; private String name; public Person(int age, String name) { this.age = age; this.name = name; } public Person() {} public int getAge() { return age; } public String getName() { return name; } @Override protected Object clone() throws CloneNotSupportedException { return (Person)super.clone(); } }
深拷贝:基本类型和引用类型都会复制;
static class Body implements Cloneable{ public Head head; public Body() {} public Body(Head head) {this.head = head;} @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } static class Head /*implements Cloneable*/{ public Face face; public Head() {} public Head(Face face){this.face = face;} } public static void main(String[] args) throws CloneNotSupportedException { Body body = new Body(new Head()); Body body1 = (Body) body.clone(); System.out.println("body == body1 : " + (body == body1) ); System.out.println("body.head == body1.head : " + (body.head == body1.head)); }
可参考:Clone和New哪个更快
Serializable接口序列化:
String类、包装类、Date类都实现了这个接口;
序列化写入对象:
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("/objectFile")); //创建输出流 out.writeObject("hello"); out.writeObject(new Date()); //写入对象
反序列化读取对象:
ObjectInputStream in = new ObjectInputStream(new FileInputStream("/objectFile")); //创建输入流 String str = (String)in.readObject(); Date date = (Date)in.readObject(); //读取对象
进一步控制:
定义readObject() 和 writeObject()方法,当ObjectOutputStream对一个对象进行序列化时,如果该对象具有writeObject()方法,则会执行;
private void writeObject(ObjectOutputStream stream) throws IOException{ stream.defaultWriteObject(); stream.writeObject(new Object()); } private void readObject(ObjectInputStream stream) throws ClassNotFoundException, IOException { stream.defaultReadObject(); Object obj = stream.readObject(); }
可参考:JAVA序列化基础知识Serializable与Externalizable的区别
Serializable序列化时不会调用默认的构造器,而Externalizable序列化时会调用默认构造器的;
二、构造方法
每个类都有一个不含参数的默认构造方法;
若自定义了一个构造方法,则默认的构造方法会消失;
子类在创建对象时,会自动先调用父类的默认构造方法;子类也可以显示的使用super()调用父类的构造方法;(所以定义类时都会显示的定义一个空构造方法,防止它丢失了子类调用不了)