【Java语言学习】之创建对象的方式种类

来源:互联网 发布:淘宝买银饰可靠吗 编辑:程序博客网 时间:2024/05/18 15:54

1、通过 new语句进行实例化一个对象:

      例如:

public class Test{       public static void main(String[] args){           Test t = new Test();    }}
2、通过反射机制创建对象

      例如:

public class Test{     public static void main(String[] args){         Class c = Class.forName("Test");         Test test = (Test)c.newInstance();     }}
3、通过clone()方法创建一个对象,但是这个类要先进行实现Cloneable接口;

public class Test  implements Cloneable {public static void main(String[] args) throws CloneNotSupportedException {Test o1 = new Test();Test o2 = (Test) o1.clone();System.out.println(o1 == o2);//结果为 falseSystem.out.println(o1.equals(o2));//结果为false ,Test类没有重写equals方法}}

4、通过反序列话的方式创建对象(过几天遇到了补上);


1 0
原创粉丝点击