【JAVA】创建对象的几种方式

版权声明:转载请注明 https://blog.csdn.net/qq_33591903/article/details/82707756

                                         创建对象的几种方式

在java中,万事万物皆对象,作为开发者,我们每天也会创建大量的对象。那么你知道有几种创建对象的方式吗?

一、使用new关键字

Student student=new Student();

这种方式是我们最熟知的方式,使用new关键字并调用无参或有参的构造方法来创建一个对象。


二、使用Class中的newInstance()方法

使用newInstance()方法会间接地调用无参构造方法

(1)第一种方式,由全类名来获取Class对象

  Student student = (Student) Class.forName("day0914.Student").newInstance();
  

(2)第二种方式,由类名.class来获取Class对象

  Student student = Student.class.newInstance();


三、使用Constructor中的newInstance()方法

  Constructor<Student> constructor=Student.class.getConstructor();
  Student student=constructor.newInstance();

(1)这种方式也会间接地调用构造方法。

(2)第二种方法和第三种方法,都是我们常说的反射机制。

(3)第二种方法也就是Class的newInstance()方法,其内部调用了Constructor的newInstance()方法。


前三种方法总结

以上方法都是需要直接或间接地的调用构造方法。


四、使用Object类的clone()方法

package day0914;

public class Student implements Cloneable {
    private String name;

    private Student() {
    }

    private Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public static void main(String args[]) {
        Student student = new Student("jack");
        try {
            Student student1 = (Student) student.clone();
            System.out.print(student1.getName());
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }


    }
}

(1)clone()方法是一个本地方法,需要实现标识接口Cloneable。

(2)每当我们使用clone()方法创建对象时,程序都会将旧对象的内容全被拷贝到新对象中,并返回给我们。

(3)使用clone()方法,不会调用构造方法。


五、使用反序列化

我们先序列化一个对象,再通过反序列化得到新对象。

package day0914;

import java.io.*;

public class Student implements Serializable {
    private String name;

    private Student() {
    }

    private Student(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

    public static void main(String args[]) {
        try {
            Student student = new Student("jack");
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("stu"));
            oos.writeObject(student);
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("stu"));
            Student student1 = (Student) ois.readObject();
            System.out.println(student1.getName());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }
}

(1)使用反序列创建对象,不会调用构造方法。

(2)使用反序列化方式创建对象,需要让我们的类实现标识接口Serializable。


最后两种方法总结:

clone()与反序列化这两种方式都不需要调用构造方法。

猜你喜欢

转载自blog.csdn.net/qq_33591903/article/details/82707756