Related
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:
Clone the object
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.
I want to achieve something like this. Declare and initialize a variable like those primitive data types.(Without having to use the new keyword)
MyClass myInstance = 123;
Similar to String. Only "String" type can do this and it's a class, too!
String myString = "A string!";
I want a way to declare some variable without using new like new MyClass(123)
Thank you!
You can't do it with custom classes.
The only classes that support such instantiation are String and the wrapper classes of the primitive types (Integer, Boolean, etc ...).
You could create instances of custom classes without the "new" if you use reflection, but then you'd be using newInstance() method of the Class class, which doesn't seem to be what you wish to achieve.
123 is a number, myInstance is an object, they are not compatible, thus you cannot assign a number (or a string, or a boolean) to a variable of the MyClass type.
The only way this would be possible in the future is if Java would allow operator overloading (like C++ for example), for now you need to stick to myInstance = new MyClass(123).
I have a string representation of a class's path. It could be any of three classes, all of which implement the same interface, Adapter, but I don't know what the value is.
"com.example.adapters.Music"
"com.example.adapters.Video"
"com.example.adapters.Photo"
Given only a variable holding one of the three strings above, how can I get a usable instance of the actual class?
You can use:
String name = "com.example.adapters.Music";
Object obj = Class.forName(name).newInstance();
You will then have to cast obj to the correct type (possibly by examining the name or by using instanceof). It is easier if your classes have a common base class (or interface that they implement) and you can use obj knowing only that it is some subclass.
This will only work if the class has a default constructor. Otherwise you will have to use reflection to get an instance of a constructor method and invoke it with the proper arguments.
If a class has a no-argument constructor, then creating an object from its package-qualified class name (for example, "java.lang.Integer") is usually done using these methods:
Class.forName
Class.newInstance
For e.g MusicClass mObj = Class.forName(<string name>).newInstance();
If arguments need to be passed to the constructor, then these alternatives may be used instead:
Class.getConstructor
Constructor.newInstance
You can use String array for holding three string
String names[]= {"com.example.adapters.Music","com.example.adapters.Video","com.example.adapters.Photo"};
Had a conversation with a coworker the other day about this.
There's the obvious using a constructor, but what are the other ways there?
There are four different ways to create objects in java:
A. Using new keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.
MyObject object = new MyObject();
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.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
C. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();
D. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
You can read them from here.
There are various ways:
Through Class.newInstance.
Through Constructor.newInstance.
Through deserialisation (uses the no-args constructor of the most derived non-serialisable base class).
Through Object.clone (does not call a constructor).
Through JNI (should call a constructor).
Through any other method that calls a new for you.
I guess you could describe class loading as creating new objects (such as interned Strings).
A literal array as part of the initialisation in a declaration (no constructor for arrays).
The array in a "varargs" (...) method call (no constructor for arrays).
Non-compile time constant string concatenation (happens to produce at least four objects, on a typical implementation).
Causing an exception to be created and thrown by the runtime. For instance throw null; or "".toCharArray()[0].
Oh, and boxing of primitives (unless cached), of course.
JDK8 should have lambdas (essentially concise anonymous inner classes), which are implicitly converted to objects.
For completeness (and Paŭlo Ebermann), there's some syntax with the new keyword as well.
Within the Java language, the only way to create an object is by calling its constructor, be it explicitly or implicitly. Using reflection results in a call to the constructor method, deserialization uses reflection to call the constructor, factory methods wrap the call to the constructor to abstract the actual construction and cloning is similarly a wrapped constructor call.
Yes, you can create objects using reflection. For example, String.class.newInstance() will give you a new empty String object.
There are five different ways to create an object in Java,
1. Using new keyword → constructor get called
Employee emp1 = new Employee();
2. Using newInstance() method of Class → constructor get called
Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
.newInstance();
It can also be written as
Employee emp2 = Employee.class.newInstance();
3. Using newInstance() method of Constructor → constructor get called
Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
4. Using clone() method → no constructor call
Employee emp4 = (Employee) emp3.clone();
5. Using deserialization → no constructor call
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();
First three methods new keyword and both newInstance() 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.
Cloning and deserialization.
Also you can use
Object myObj = Class.forName("your.cClass").newInstance();
This should be noticed if you are new to java, every object has inherited from Object
protected native Object clone() throws CloneNotSupportedException;
Also, you can de-serialize data into an object. This doesn't go through the class Constructor !
UPDATED : Thanks Tom for pointing that out in your comment ! And Michael also experimented.
It goes through the constructor of the most derived non-serializable superclass.
And when that class has no no-args constructor, a InvalidClassException is thrown upon de-serialization.
Please see Tom's answer for a complete treatment of all cases ;-)
is there any other way of creating an object without using "new" keyword in java
There is a type of object, which can't be constructed by normal instance creation mechanisms (calling constructors): Arrays. Arrays are created with
A[] array = new A[len];
or
A[] array = new A[] { value0, value1, value2 };
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
A[] array = (A[]) Array.newInstance(A.class, len);
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.
Other ways if we are being exhaustive.
On the Oracle JVM is Unsafe.allocateInstance() which creates an instance without calling a constructor.
Using byte code manipulation you can add code to anewarray, multianewarray, newarray or new. These can be added using libraries such as ASM or BCEL. A version of bcel is shipped with Oracle's Java. Again this doesn't call a constructor, but you can call a constructor as a seperate call.
Reflection:
someClass.newInstance();
Reflection will also do the job for you.
SomeClass anObj = SomeClass.class.newInstance();
is another way to create a new instance of a class. In this case, you will also need to handle the exceptions that might get thrown.
using the new operator (thus invoking a constructor)
using reflection clazz.newInstance() (which again invokes the constructor). Or by clazz.getConstructor(..).newInstance(..) (again using a constructor, but you can thus choose which one)
To summarize the answer - one main way - by invoking the constructor of the object's class.
Update: Another answer listed two ways that do not involve using a constructor - deseralization and cloning.
There are FIVE different ways to create objects in Java:
1. Using `new` keyword:
This is the most common way to create an object in Java. Almost 99% of objects are created in this way.
MyObject object = new MyObject();//normal way
2. By Using Factory Method:
ClassName ObgRef=ClassName.FactoryMethod();
Example:
RunTime rt=Runtime.getRunTime();//Static Factory Method
3. By Using Cloning Concept:
By using clone(), the clone() can be used to create a copy of an existing object.
MyObjectName anotherObject = new MyObjectName();
MyObjectName object = anotherObjectName.clone();//cloning Object
4. 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.
MyObjectName object = (MyObjectNmae) Class.forName("PackageName.ClassName").newInstance();
Example:
String st=(String)Class.forName("java.lang.String").newInstance();
5. Using object deserialization:
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStreamName inStream = new ObjectInputStreamName(anInputStream );
MyObjectName object = (MyObjectNmae) inStream.readObject();
You can also clone existing object (if it implements Cloneable).
Foo fooClone = fooOriginal.clone ();
Method 1
Using new keyword. This is the most common way to create an object in java. Almost 99% of objects are created in this way.
Employee object = new Employee();
Method 2
Using Class.forName(). Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. callingClass.forName("ExampleClass").newInstance() it is equivalent to calling new ExampleClass()), on which you can call the methods that the class defines, access the visible fields etc.
Employee object2 = (Employee) Class.forName(NewEmployee).newInstance();
Class.forName() will always use the ClassLoader of the caller, whereas ClassLoader.loadClass() can specify a different ClassLoader. I believe that Class.forName initializes the loaded class as well, whereas the ClassLoader.loadClass() approach doesn’t do that right away (it’s not initialized until it’s used for the first time).
Another must read:
Java: Thread State Introduction with Example
Simple Java Enum Example
Method 3
Using clone(). The clone() can be used to create a copy of an existing object.
Employee secondObject = new Employee();
Employee object3 = (Employee) secondObject.clone();
Method 4
Using newInstance() method
Object object4 = Employee.class.getClassLoader().loadClass(NewEmployee).newInstance();
Method 5
Using Object Deserialization. Object Deserialization is nothing but creating an object from its serialized form.
// Create Object5
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(object3);
oout.flush();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("crunchify.txt"));
Employee object5 = (Employee) ois.readObject();
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.
Depends exactly what you mean by create but some other ones are:
Clone method
Deserialization
Reflection (Class.newInstance())
Reflection (Constructor object)
there is also ClassLoader.loadClass(string) but this is not often used.
and if you want to be a total lawyer about it, arrays are technically objects because of an array's .length property. so initializing an array creates an object.
We can create an objects in 5 ways:
by new operator
by reflection (e.g. Class.forName() followed by Class.newInstance())
by factory method
by cloning
by reflection api
We can also create the object in this way:-
String s ="Hello";
Nobody has discuss it.
Had a conversation with a coworker the other day about this.
There's the obvious using a constructor, but what are the other ways there?
There are four different ways to create objects in java:
A. Using new keyword
This is the most common way to create an object in java. Almost 99% of objects are created in this way.
MyObject object = new MyObject();
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.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
C. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = (MyObject) anotherObject.clone();
D. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
You can read them from here.
There are various ways:
Through Class.newInstance.
Through Constructor.newInstance.
Through deserialisation (uses the no-args constructor of the most derived non-serialisable base class).
Through Object.clone (does not call a constructor).
Through JNI (should call a constructor).
Through any other method that calls a new for you.
I guess you could describe class loading as creating new objects (such as interned Strings).
A literal array as part of the initialisation in a declaration (no constructor for arrays).
The array in a "varargs" (...) method call (no constructor for arrays).
Non-compile time constant string concatenation (happens to produce at least four objects, on a typical implementation).
Causing an exception to be created and thrown by the runtime. For instance throw null; or "".toCharArray()[0].
Oh, and boxing of primitives (unless cached), of course.
JDK8 should have lambdas (essentially concise anonymous inner classes), which are implicitly converted to objects.
For completeness (and Paŭlo Ebermann), there's some syntax with the new keyword as well.
Within the Java language, the only way to create an object is by calling its constructor, be it explicitly or implicitly. Using reflection results in a call to the constructor method, deserialization uses reflection to call the constructor, factory methods wrap the call to the constructor to abstract the actual construction and cloning is similarly a wrapped constructor call.
Yes, you can create objects using reflection. For example, String.class.newInstance() will give you a new empty String object.
There are five different ways to create an object in Java,
1. Using new keyword → constructor get called
Employee emp1 = new Employee();
2. Using newInstance() method of Class → constructor get called
Employee emp2 = (Employee) Class.forName("org.programming.mitra.exercises.Employee")
.newInstance();
It can also be written as
Employee emp2 = Employee.class.newInstance();
3. Using newInstance() method of Constructor → constructor get called
Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
4. Using clone() method → no constructor call
Employee emp4 = (Employee) emp3.clone();
5. Using deserialization → no constructor call
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();
First three methods new keyword and both newInstance() 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.
Cloning and deserialization.
Also you can use
Object myObj = Class.forName("your.cClass").newInstance();
This should be noticed if you are new to java, every object has inherited from Object
protected native Object clone() throws CloneNotSupportedException;
Also, you can de-serialize data into an object. This doesn't go through the class Constructor !
UPDATED : Thanks Tom for pointing that out in your comment ! And Michael also experimented.
It goes through the constructor of the most derived non-serializable superclass.
And when that class has no no-args constructor, a InvalidClassException is thrown upon de-serialization.
Please see Tom's answer for a complete treatment of all cases ;-)
is there any other way of creating an object without using "new" keyword in java
There is a type of object, which can't be constructed by normal instance creation mechanisms (calling constructors): Arrays. Arrays are created with
A[] array = new A[len];
or
A[] array = new A[] { value0, value1, value2 };
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
A[] array = (A[]) Array.newInstance(A.class, len);
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.
Other ways if we are being exhaustive.
On the Oracle JVM is Unsafe.allocateInstance() which creates an instance without calling a constructor.
Using byte code manipulation you can add code to anewarray, multianewarray, newarray or new. These can be added using libraries such as ASM or BCEL. A version of bcel is shipped with Oracle's Java. Again this doesn't call a constructor, but you can call a constructor as a seperate call.
Reflection:
someClass.newInstance();
Reflection will also do the job for you.
SomeClass anObj = SomeClass.class.newInstance();
is another way to create a new instance of a class. In this case, you will also need to handle the exceptions that might get thrown.
using the new operator (thus invoking a constructor)
using reflection clazz.newInstance() (which again invokes the constructor). Or by clazz.getConstructor(..).newInstance(..) (again using a constructor, but you can thus choose which one)
To summarize the answer - one main way - by invoking the constructor of the object's class.
Update: Another answer listed two ways that do not involve using a constructor - deseralization and cloning.
There are FIVE different ways to create objects in Java:
1. Using `new` keyword:
This is the most common way to create an object in Java. Almost 99% of objects are created in this way.
MyObject object = new MyObject();//normal way
2. By Using Factory Method:
ClassName ObgRef=ClassName.FactoryMethod();
Example:
RunTime rt=Runtime.getRunTime();//Static Factory Method
3. By Using Cloning Concept:
By using clone(), the clone() can be used to create a copy of an existing object.
MyObjectName anotherObject = new MyObjectName();
MyObjectName object = anotherObjectName.clone();//cloning Object
4. 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.
MyObjectName object = (MyObjectNmae) Class.forName("PackageName.ClassName").newInstance();
Example:
String st=(String)Class.forName("java.lang.String").newInstance();
5. Using object deserialization:
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStreamName inStream = new ObjectInputStreamName(anInputStream );
MyObjectName object = (MyObjectNmae) inStream.readObject();
You can also clone existing object (if it implements Cloneable).
Foo fooClone = fooOriginal.clone ();
Method 1
Using new keyword. This is the most common way to create an object in java. Almost 99% of objects are created in this way.
Employee object = new Employee();
Method 2
Using Class.forName(). Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. callingClass.forName("ExampleClass").newInstance() it is equivalent to calling new ExampleClass()), on which you can call the methods that the class defines, access the visible fields etc.
Employee object2 = (Employee) Class.forName(NewEmployee).newInstance();
Class.forName() will always use the ClassLoader of the caller, whereas ClassLoader.loadClass() can specify a different ClassLoader. I believe that Class.forName initializes the loaded class as well, whereas the ClassLoader.loadClass() approach doesn’t do that right away (it’s not initialized until it’s used for the first time).
Another must read:
Java: Thread State Introduction with Example
Simple Java Enum Example
Method 3
Using clone(). The clone() can be used to create a copy of an existing object.
Employee secondObject = new Employee();
Employee object3 = (Employee) secondObject.clone();
Method 4
Using newInstance() method
Object object4 = Employee.class.getClassLoader().loadClass(NewEmployee).newInstance();
Method 5
Using Object Deserialization. Object Deserialization is nothing but creating an object from its serialized form.
// Create Object5
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(object3);
oout.flush();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("crunchify.txt"));
Employee object5 = (Employee) ois.readObject();
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.
Depends exactly what you mean by create but some other ones are:
Clone method
Deserialization
Reflection (Class.newInstance())
Reflection (Constructor object)
there is also ClassLoader.loadClass(string) but this is not often used.
and if you want to be a total lawyer about it, arrays are technically objects because of an array's .length property. so initializing an array creates an object.
We can create an objects in 5 ways:
by new operator
by reflection (e.g. Class.forName() followed by Class.newInstance())
by factory method
by cloning
by reflection api
We can also create the object in this way:-
String s ="Hello";
Nobody has discuss it.