Several methods of creating objects in Java

Sometimes, you may encounter such interview questions, such as:

What are several ways to create objects in Java?

In addition to new, how many ways can Java create objects?

Combined with examples, this paper gives several methods of creating objects in Java, here we go~~~~

Create with new

This is the most commonly used one. For example:

Book book = new Book();

Examples are as follows:

Use object clone()

If you want to call the clone method, the object needs to implement the clonable interface and override the clone () method.

The modified book class is as follows:

Test code

Use class newInstance()

You can use class directly forName("xxx.xx"). Newinstance() method or XXX class. Newinstance() completed.

Use the constructor newInstance()

You can specify a constructor to create, such as selecting the first constructor to create; You can also specify the constructor parameter type to create.

Use class Newinstance() or constructor Newinstance(), which is essentially the same, adopts the reflection mechanism.

Using deserialization

Of course, in addition to the above methods, you can also use JNI and other methods to create objects, which will not be listed here.

The complete example code is as follows:

CreateObjectExample. java

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>