Java中创建一个类的所有方式

Java中到底有多少种方法可以创建一个对象呢?

用再熟悉不过的Student类开干:

public class Student {
	private int age;
	private String name;

	public Student() {
	}

	public Student(int age, String name) {
		this.age = age;
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}
1、使用new关键字,调用任意的构造函数就可以实现。
	public static void main(String[] args) {

		Student stu1 = new Student();
		Student stu2 = new Student(18, "小红");
		
	}
2、通过反射,使用Class类的newInstance方法,调用了无参构造函数。
	public static void main(String[] args) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException {

		Student stu1 = Student.class.newInstance();
		Student stu2 = (Student) Class.forName("test.Student").newInstance();

	}

这里注意,如果没有无参构造函数,上面就会报错的。
在这里插入图片描述

3、通过反射,使用Constructor类的newInstance方法,可以调用任何构造方法。
	public static void main(String[] args) throws NoSuchMethodException,
			SecurityException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {

		Student stu1 = Student.class.getConstructor().newInstance();
		Student stu2 = Student.class.getConstructor().newInstance(18, "小红");
		
	}
4、使用clone方法,没有调用构造函数。

要使用clone方法,要先实现Cloneable接口并重写Object中的clone方法。 在不实现Cloneable接口的实例上调用对象的克隆方法导致抛出异常CloneNotSupportedException,注意,此接口不包含clone方法。 因此,只能通过实现该接口的实例来克隆对象是不可能的,还要重写clone方法。

public class Student implements Cloneable {
	private int age;
	private String name;

	public Student() {
	}

	public Student(int age, String name) {
		this.age = age;
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		Student stu = null;
		try {
			stu = (Student) super.clone();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stu;
	}

	@Override
	public String toString() {
		return "[name=" + name + ", age=" + age + "]";
	}
}

	public static void main(String[] args) throws CloneNotSupportedException {

		Student stu1 = new Student(18, "是小红鸭");
		Student stu2 = (Student) stu1.clone();

		System.out.println(stu1.toString());
		System.out.println(stu2.toString());
	}

在这里插入图片描述

5、使用反序列化,将原来序列化到文件中的对象信息反序列化,没有调用构造函数。

不知道序列化与反序列化的看这里:https://blog.csdn.net/qq_42570601/article/details/103396656

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yelvens

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值