Different Ways to Create an Object in Java
Different Ways To Create An Object In Java
Java is an object-oriented programming language and its source code is organized into classes, which contain the data and methods that operate on the data. To create objects of a class, a special type of method called a constructor is used. There are several ways to create an object in Java. Let's take a look at some of them.
Using New Keyword
One of the most common and simplest ways of creating an object in Java is using the new keyword. This keyword allocates memory for the object and returns a reference to the object. Following is a simple syntax of creating an object using the new keyword.
ClassName object = new ClassName();
Using newInstance() Method
The newInstance() method of the Class class can be used to create an object of a class. This method is used to instantiate a class by passing its string name as an argument. The following code snippet shows how to use this method to create an object:
Class c = Class.forName("classname");
Object o = c.newInstance();
Using clone() Method
The clone() method is used to create a copy of an existing object. The syntax for creating an object using the clone() method is as follows:
Object cloneObject = originalObject.clone();
Using Deserialization
Deserialization is the process of reconstructing an object from a serialized state. An object can be serialized by calling the writeObject() method of the ObjectOutputStream class. Deserialization can be done by calling the readObject() method of the ObjectInputStream class. Here is an example of deserializing an object:
//serialize the object
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("filename"));
out.writeObject(object);
out.close();
//deserialize the object
ObjectInputStream in = new ObjectInputStream(new FileInputStream("filename"));
Object object = in.readObject();
in.close();
Conclusion
We have seen different ways to create an object in Java. These techniques can be used according to the requirement. Using the new keyword is the most commonly used approach for creating an object in Java. The other techniques discussed here are also useful for different scenarios.