java 创建对象override_java创建对象的4种方法

方法1:静态编码&编译(new)

最常用的就是静态编写一个类,然后new一个对象

public class New {

public static void main(String[] args) {

New n = new New();

}

}

方法2:克隆(clone)

java提供克隆的手段来复制一个对象

浅克隆:

1.被复制的类需要实现Clonenable接口

2.Override clone()

public class Clone implements Cloneable{

private String name;

public Clone(String name){

this.name = name;

}

public void printName(){

System.out.println("My name is "+ name);

}

public void setName(String name) {

this.name = name;

}

@Override

public Object clone() throws CloneNotSupportedException{

return super.clone();

}

public static void main(String[] args) {

try {

Clone c = new Clone("Edwin Xu");

c.setName("Edwin Wang");

Clone clone = (Clone) c.clone();

clone.printName(); //My name is Edwin Wang

}catch (Exception e){

e.printStackTrace();

}

}

}

对于属性中有引用类型的,需要让该引用类型也继承Cloneable并重写clone(), 以实现深克隆。

如果类中有过多的引用类型就会很麻烦。

方法3:序列化与反序列化

序列化就是把对象写到流的过程,被写入流的对象是原对象的拷贝。

通过反序列化从流中重写构建出该对象,实现了真正的深度克隆。

public class Deserialization implements Serializable {

private static final long serialVersionUID = 1L;

private String name;

public Deserialization(String name){

this.name =name;

}

public void printName(){

System.out.println("My Name Is "+name);

}

public static void main(String[] args) {

try {

Deserialization d = new Deserialization("Edwin");

//序列化:打开一个流,写入

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.obj"));

out.writeObject(d);

out.close();

//反序列化:从流中取出来

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));

Deserialization d1 = (Deserialization)in.readObject();

in.close();

d1.printName();//My Name Is Edwin

}catch (Exception e){

e.printStackTrace();

}

}

}

方法4:反射

反射提供一种动态创建对象的方式

package reflection;

import java.lang.reflect.Constructor;

public class Reflection {

public Reflection(){

System.out.println("initializing");

}

public static void main(String[] args) {

try {

//方式1:Class.forName(full path)

Reflection r = (Reflection) Class.forName("reflection.Reflection").newInstance();

//方式2:ClassName.class

Reflection c1 = Reflection.class.newInstance();

//方式3:利用Constructor

Constructor con = Reflection.class.getConstructor();

Reflection r2 = con.newInstance();

}catch (Exception e){

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值