[java] What are the ways to create objects in Java?

foreword

In Java, there are many ways to create objects. This article will introduce the following six ways to create objects in detail:

1. Use the new keyword

The new keyword is the most commonly used way of creating objects in Java. The new keyword instantiates an object by calling the constructor of the class.
Examples are as follows:

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

Person person = new Person("小明", 18);

2. Use the newInstance() method of Class

The newInstance() method of Class can create a new instance of a class at runtime. It is equivalent to using the new operator, but the syntax is more dynamic.
Examples are as follows:

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

try {
    
    
    Person person = Person.class.newInstance();
    person.name = "小明";
    person.age = 18;
} catch (Exception e) {
    
    
    e.printStackTrace();
}

3. Use Constructor's newInstance() method

Constructor's newInstance() method can create a new instance of a class at runtime, and can pass in the parameters of the constructor. This method is more flexible than Class's newInstance() method, because you can choose different constructors.
Examples are as follows:

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

try {
    
    
    Constructor<Person> constructor = Person.class.getConstructor(String.class, int.class);
    Person person = constructor.newInstance("小明", 18);
} catch (Exception e) {
    
    
    e.printStackTrace();
}

4. Use the clone() method

The clone() method can create a copy of the object, and the clone() method can be overridden to implement deep cloning.
Examples are as follows:

public class Person implements Cloneable {
    
    
    String name;
    int age;

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

    @Override
    protected Object clone() throws CloneNotSupportedException {
    
    
        return super.clone();
    }
}

Person person = new Person("小明", 18);
Person clone = null;
try {
    
    
    clone = (Person) person.clone();
} catch (CloneNotSupportedException e) {
    
    
    e.printStackTrace();
}

5. Use deserialization

Deserialization is the process of recovering an object from a byte stream. After serialization, the object can be stored in a file or network, and then restored into an object by deserialization.
Examples are as follows:

public class Person implements Serializable {
    
    
    String name;
    int age;

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

Person person = new Person("小明", 18);

try {
    
    
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.dat"));
    oos.writeObject(person);
    oos.close();
    
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.dat"));
    Person clone = (Person) ois.readObject();
    ois.close();
} catch (Exception e) {
    
    
    e.printStackTrace();
}

6. Use the factory pattern

The factory pattern can decouple the creation and use of objects. Objects can be generated more flexibly by defining an object factory.
Examples are as follows:

public interface Animal {
    
    
    String getName();
}

public class Cat implements Animal {
    
    
    @Override
    public String getName() {
    
    
        return "Cat";
    }
}

public class Dog implements Animal {
    
    
    @Override
    public String getName() {
    
    
        return "Dog";
    }
}

public class AnimalFactory {
    
    
    public Animal createAnimal(String type) {
    
    
        switch (type) {
    
    
            case "Cat":
                return new Cat();
            case "Dog":
                return new Dog();
            default:
                throw new IllegalArgumentException("Unsupported animal type: " + type);
        }
    }
}

AnimalFactory factory = new AnimalFactory();
Animal cat = factory.createAnimal("Cat");
Animal dog = factory.createAnimal("Dog");

Summarize

This article introduces six common ways of creating objects in Java, namely using new关键字、Class的newInstance()方法、Constructor的newInstance()方法、clone()方法、反序列化、工厂模式and so on. In actual development, different creation methods can be selected according to specific business scenarios.

Guess you like

Origin blog.csdn.net/u011397981/article/details/130394478