Five ways to create Java objects, how many do you know?

Follow the "Java Architecture Stack" WeChat official account and reply with the password [Java Interview Questions] to get the interview questions from big companies

Recently, a friend went for an interview and was asked by the interviewer the question "What are the ways to create objects in Java?" Naturally, this little friend said the new method very quickly, but the interviewer continued to ask what other methods there were, and he hesitated for a long time without knowing. So is this problem difficult? Today, Brother Bo is here to summarize the ways to create objects in Java. Come and take a look.

 How to create objects

1.new keyword

Everyone must be very familiar with this method. We can create an object directly through the new keyword. Through this method, we can call the parameterless constructor or the parameterized constructor. The example code is as follows:

public class Test {
    public static void main(String[] args) {
        User user1 = new User();
        User user2 = new User("张三", "123456");
    }
 }

2. Deserialization

If we want to deserialize and create an object, we must first serialize the object. So what is serialization? To put it bluntly, it is the process of converting Java objects into byte streams or character streams. Deserialization is the process of converting byte stream or character stream objects into Java objects.

A file that has not been serialized is empty, as shown in the following figure:

public class Test {
    public static void main(String[] args) throws Exception {
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D:\\Test\\userFile.txt"));
        User user = new User("张三","123456");
        objectOutputStream.writeObject(user);
        objectOutputStream.close();
    }
}

When we run the above code, the following will appear in userFile.txt:

At this point, if we execute the following code again:

public class Test {
    public static void main(String[] args) throws Exception {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D:\\Test01\\userFile.txt"));
        User user = (User) objectInputStream.readObject();
        System.out.println(user.username()+","+user.password());
        objectInputStream.close();
    }
}

You will get the following content:

From this we can know that this User object is obtained from the previous userFile.txt file.

3. Call newInstance method

There is a newInstance method in the class class, which calls the public no-argument constructor in the class. When we use this method to create an object, the example code is as follows:

public class Test {
    public static void main(String[] args) throws Exception {
        User user = (User) Class.forName("User").newInstance();
    }
}

4. Constructor.newInstance

In addition, in the Constructor class, there is also a newInstance method to help us create objects. Through this method, we can call parameterized construction or private construction methods. The sample code is as follows:

public class Test {
    public static void main(String[] args) throws Exception {
        Constructor<User> userConstructor = User.class.getConstructor();
        User user = userConstructor.newInstance();
    }
}

5. Clone method

Finally, we can also use the clone() method to create a new object. But everyone should note that the prerequisite for using this method is that we must first let the class implement the Cloneable interface and rewrite the clone method of Object (because this method in Object is protected and cannot be called externally if it is not rewritten). The example code is as follows:

public class User  implements Cloneable{
    @Override
    public User clone() throws CloneNotSupportedException {
        return (User) super.clone();
   }
}

public class Test {
    public static void main(String[] args) throws Exception {
        User user1 = new User();
        User user2 = user1.clone();
    }
}

 Conclusion

The above are the five methods of creating objects introduced by Brother Bo to his friends. Now do you know what methods there are for creating Java objects? If the interviewer asks you again in the future how to create objects in Java, you can tell him these methods. Pay attention to the Java architecture stack, and you will get useful information every day!

Guess you like

Origin blog.csdn.net/weixin_41692221/article/details/131415190