Reputation:
One of my lecturer said that there are some other ways to create/instantiate objects in Java rather than using the "new" keyword. If it is possible, please guide me how to do so?
Upvotes: 3
Views: 193
Reputation: 5072
Looks like more of an interview question but I will still answer it :)
Reflection is one way to create instance of an object. You can Class.forName("abc.de.FGH").newInstance()
to create an instance
The other way is to use deserialization assuming an object is serialized.
new ObjectInputStream(anInputStream ).readObject();
One other way I could think of it is cloning.
Object otherObject = mainObject.clone();
Primitive Types, String Literals are other ways of creating object though they are specific to certain types.
Upvotes: 2
Reputation: 17802
Yes, objects are instantiated using the "new" keyword. But this doesn't mean, they can be instantiated only this way.
Have a look at the following code(Java):
public class SimpleClass {
public static SimpleClass instantiateAnObjectForMe() {
return new SimpleClass();
}
}
And then somewhere else in your project, You can create the instance of the class by calling the static method I wrote above like so:
SimpleClass simpleObject = SimpleClass.instantiateAnObjectForMe();
I hope you get the idea :)
Upvotes: 1
Reputation: 1737
One example is Object.class.newInstance()
. There are more complex ways using java reflection, here is one of many tutorials.
Upvotes: 0
Reputation: 3214
Yes, you could create object using reflection or with autoboxing mechanism or any other literals built in to language.
String x = "abc";
int[] y = {1, 2, 3}
Object z = classObject.newInstnce();
Upvotes: 1