There are number of ways to create objects in java. But today i am going to show 4 mostly used ways to create objects in java.
The 4 ways to create object are :
- Using new operator
- Using Class.forName
- Cloning
- Deserialization
The first way is very common and mostly used by the developers community which using new operator. Almost all objects are created using this new operator. Here is the simple example code snippet to show the way.
MyObject obj = new MyObject();
The second way is using Class.forName. This is not so popular as much the first way but in some areas of codding we need this to be used. When we know the class name and the class the public default constructor then we can create the object using this way.
MyObject obj = (MyObject)Class.forName("javaprg.coreprg.MyObject").newInstance();
The third way is using cloning where we use clone(). Generally the clone() is used to make a copy of an existing object. But here I will show you how to make a new object using clone(). See the below code snippet
MyObject myObj = new MyObject();
MyObject newObj = (MyObject) myObj.clone();
The fourth way is to create an object is using object deserialization. Well object deserialization is about creating an object form its own serialized form. Below is a small code snippet to show the process:
ObjectInputStream ois = new ObjectInputStream(anyInputStream);
MyObject obj = (MyObject)ois.readObject();
So here are the for mostly used way to create the object in java programming language.
Thanks for watching.