3

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.

JAVA_LOVER
  • 31
  • 2

4 Answers4

8

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

Vladislav Varslavans
  • 2,552
  • 3
  • 16
  • 32
1

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.

Nowhere Man
  • 18,291
  • 9
  • 17
  • 38
0

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

Boc Dev
  • 193
  • 1
  • 7
-1

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.

SwissCodeMen
  • 3,359
  • 4
  • 15
  • 26
  • 1
    That is only correct for the "regular" ways. Neither cloning nor deserialization actually go through a constructor. They use Java black magic to bypass all of those mechanisms and they use mechanisms built directly into the language instead. – Zabuzard Apr 24 '20 at 19:53