简体   繁体   中英

Is constructor the only way to create the object of a class in JAVA?

If a constructor is the only way to create the object of a class then how String name = "Java"; is able to create an object of String class even without using constructor.

No. Constructor is not the only way.

There are at least two more ways:

  1. Clone the object
  2. Serialize and then deserialize object.

Though in case with your example - neither of these is used.

In this case Java uses string pool

There is another way of creating objects via

  • Class.forName("fully.qualified.class.name.here").newInstance()

  • Class.forName("fully.qualified.class.name.here").getConstuctor().newInstance()

but they call constructor under the hood.

Other ways to create objects are cloning via clone() method and deserialization.

I suppose in a loop-hole type of way you could use the class object too:

// Get the class object using an object you already have   
Class<?> clazz = object.getClass();

// or get class object using the type
Class<?> clazz = Object.class;

// Get the constructor object (give arguments 
// of Class objects of types if the constructor takes arguments)
Constructor<?> constructor = clazz.getConstructor();

// then invoke it (and pass arguments if need be)
Object o = constructor.newInstance();

I mean you still use the constructor so it probably doesn't really count. But hey, its there!

Java doc link for Class object

YES, each time a new object is created, at least one constructor will be invoked.

Look at this tutorial , this will explain all with objects, classes and constructors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM