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,775
  • 4
  • 18
  • 33
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
  • 19,170
  • 9
  • 17
  • 42
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
  • 313
  • 2
  • 8
-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
  • 4,222
  • 8
  • 24
  • 34
  • 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