Had a conversation with a coworker the other day about this.
There's the obvious which is to use a constructor, but what other ways are there?
Had a conversation with a coworker the other day about this.
There's the obvious which is to use a constructor, but what other ways are there?
From an API user perspective, another alternative to constructors are static factory methods (like BigInteger.valueOf()), though for the API author (and technically "for real") the objects are still created using a constructor.
There are four different ways to create objects in java:
A. Using
new
keywordThis is the most common way to create an object in java. Almost 99% of objects are created in this way.
B. Using
Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
C. Using
clone()
The clone() can be used to create a copy of an existing object.
D. Using
object deserialization
Object deserialization is nothing but creating an object from its serialized form.
You can read from here
There are five different ways to create an object in Java,
1. Using
new
keyword → constructor get called2. Using
newInstance()
method ofClass
→ constructor get calledIt can also be written as
3. Using
newInstance()
method ofConstructor
→ constructor get called4. Using
clone()
method → no constructor call5. Using deserialization → no constructor call
First three methods
new
keyword and bothnewInstance()
include a constructor call but later two clone and deserialization methods create objects without calling the constructor.All above methods have different bytecode associated with them, Read Different ways to create objects in Java with Example for examples and more detailed description e.g. bytecode conversion of all these methods.
However one can argue that creating an array or string object is also a way of creating the object but these things are more specific to some classes only and handled directly by JVM, while we can create an object of any class by using these 5 ways.
This should be noticed if you are new to java, every object has inherited from Object
protected native Object clone() throws CloneNotSupportedException;
There is a type of object, which can't be constructed by normal instance creation mechanisms (calling constructors): Arrays. Arrays are created with
or
As Sean said in a comment, this is syntactically similar to a constructor call and internally it is not much more than allocation and zero-initializing (or initializing with explicit content, in the second case) a memory block, with some header to indicate the type and the length.
When passing arguments to a varargs-method, an array is there created (and filled) implicitly, too.
A fourth way would be
Of course, cloning and deserializing works here, too.
There are many methods in the Standard API which create arrays, but they all in fact are using one (or more) of these ways.
Cloning and deserialization.