//待创建的类
/**
* 创建对象的方式1
* colone-------克隆
*/
public class Hello implements Cloneable {
public void sayHello(){
System.out.println("hello world");
}
public static void main(String[] args) {
Hello h1 = new Hello();
try {
Hello h2 = (Hello) h1.clone();
h2.sayHello();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class Hello_2 implements Serializable {
/**
* 创建对象的方式2
* 序列化
*/
public static void main(String[] args) {
Hello h = new Hello();
//使用物理内存存储
File f = new File("D:\\File-Copy\\one\\hello.obj");
try {
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
//序列化对象,写入磁盘中
oos.writeObject(h);
//反序列化对象
Hello newHello = (Hello) ois.readObject();
//测试方法
newHello.sayHello();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public class NewClass_1 {
public static void main(String[] args) {
/**
* 创建对象的方式3,
* new
/
Hello h = new Hello();
h.sayHello();
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
* 创建对象方式4
* 反射
*/
public class NewClass_2 {
public static void main(String[] args) {
try {
Class heroClass = Class.forName("cn.itcast.demo.Hello");
Hello h = (Hello) heroClass .newInstance();
h.sayHello();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
总结,java创建对象的四种方式有序列化,new,反射,克隆.