Java创建对象的五种方式

本文详细介绍了在Java中创建对象的五种常见方法:使用new关键字、Class类的newInstance()、Constructor类的新实例、clone()方法以及反序列化。每种方法都附带了示例代码,并指出了可能抛出的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.new一个对象,使用new关键字(常用)

public class Example{
    public void say(){
    	System.out.println("zrc");
    }
	public static void main(String[] args){
		Example e1=new Example();
		e1.say();
	}
}

2.使用Class类的newInstance(),会抛出InstantiationException和IllegalAccessException

public class Example{
    public void say(){
    	System.out.println("zrc");
    }
	public static void main(String[] args) throws InstantiationException, IllegalAccessException{
		Example e2=Example.class.newInstance();
		e2.say();
	}
}

3.使用Constructor类的newInstance(),会抛出六个异常( NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException)

public class Example{
    public void say(){
    	System.out.println("zrc");
    }
	public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
	    Constructor<Example> constructor=Example.class.getConstructor();
	    Example e3=constructor.newInstance();
		e3.say();
	}
}

4.使用创建好的对象的clone()来去创造新的对象。会抛出CloneNotSupportedException,同时仍需继承Cloneable接口。

public class Example implements Cloneable{
    public void say(){
    	System.out.println("zrc");
    }
	public static void main(String[] args) throws CloneNotSupportedException{
	    Example e=new Example();
	    Example e4=(Example) e.clone();
		e4.say();
	}
}

5.使用反序列化,实现Serializable接口,会抛出FileNotFoundException,IOException,ClassNotFoundException等异常

public class Example implements Serializable{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public void say(){
    	System.out.println("zrc");
    }
	public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException{
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
		Example e5 = (Example) in.readObject();
		e5.say();
	}
}

public class Example implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
public void say(){
System.out.println(“zrc”);
}
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException{
ObjectInputStream in = new ObjectInputStream(new FileInputStream(“data.obj”));
Example e5 = (Example) in.readObject();
e5.say();
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值