JAVA_LOVER
JAVA_LOVER

Reputation: 31

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.

Upvotes: 3

Views: 173

Answers (4)

Boc Dev
Boc Dev

Reputation: 333

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

Upvotes: 0

Nowhere Man
Nowhere Man

Reputation: 19575

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.

Upvotes: 1

Vladislav Varslavans
Vladislav Varslavans

Reputation: 2944

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

Upvotes: 8

SwissCodeMen
SwissCodeMen

Reputation: 4895

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.

Upvotes: -1

Related Questions