One of common and interesting interview question is the different ways to create an Object in Java. We all know how to create objects of any class (isn’t it!!?) Simplest is using new keyword, but is it the only way to create an Object? Simple Answers is NO, there are many ways we can create Object of a Class.
I will try to list down few approaches which can used to create an object (to best of my knowledge).
Different approaches to create an Object.
We will look and study 5 approaches which can be used for object creation. So let’s begin.
Method #1 – Using new keyword
This is the most common approach the developers use in Java to create an Object. I read somewhere that this approach is also called static instance creation.
GoyalsBit obj = new GoyalsBit();
Method #2- Using Class.forName ()
If we know the name of the class then this method is useful but point to be noted here is that the class should have a public constructor. Now doesn’t it sound familiar!! Yes if you have worked in JDBC then we use this method to connect to DB. Class.forName actually loads the class in Java but doesn’t create any Object. To Create an Object of the Class you have to use newInstance method. Calling Class.forName(“NameofClass”).newInstance() is equivalent to declaring object using new keyword.
Method #3- Using clone ()
This method can be used to create a copy of an existing object. Object.clone() is a native method which translates into instructions for allocating the memory and copying the data
GoyalsBit obj = new GoyalsBit ();
GoyalsBit object1 = (GoyalsBit) obj.clone();
As I have already marked in bold that using this technique we are only creating clone of an existing object and not new object. Class need to implement Cloneable Interface otherwise it will throw CloneNotSupportedException.
Method #4- Using Deserialization ()
Deserialization is the process of creating the new object on the remote machine from its serialize form.
ObjectInputStream inStream =new ObjectInputStream(anInputStream );
GoyalsBit object (GoyalsBit) inStream.readObject();
Method #5- Using ClassLoader()
We can also use Class Loader to create Object of a Class. This way is somewhat same as Class.forName option.
Object obj = GoyalsBit.class.getClassLoader().loadClass(“com.test.GoyalsBit “).newInstance();
I have shared the different ways to create an object in Java. In case there are some more, then please share them in comments section.