Java创建对象的五种方式

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 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();
}
}

你可能感兴趣的:(Java)