There are several ways by which we can create objects of a class in java as we all know a class provides the blueprint for objects, you create an object from a class. This concept is under-rated and sometimes proves to be beneficial as this concept is bypassed by many programmers and sometimes even do ask from interview perceptive.
Methods:
There are many different ways to create objects in Java. Let us list them later discussing later taking individually with the help of programs to illustrate internal working by which we can create objects in Java.
- Using new keyword
- Using new instance
- Using clone() method
- Using deserialization
- Using newInstance() method of Constructor class
Let us discuss them one by one and implement the same by appending a clean java program for the same.
Method 1: Using new keyword
Using the new keyword in java is the most basic way to create an object. This is the most common way to create an object in java. Almost 99% of objects are created in this way. By using this method we can call any constructor we want to call (no argument or parameterized constructors).
Example
Java
class GFG {
String name = "GeeksForGeeks" ;
public static void main(String[] args)
{
GFG obj = new GFG();
System.out.println(obj.name);
}
}
|
Method 2: Using new instance
If we know the name of the class & if it has a public default constructor we can create an object Class.forName. We can use it to create the Object of a Class. 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 the new Instance Method of the Class.
Example
Java
class GFG {
String name = "GeeksForGeeks" ;
public static void main(String[] args)
{
try {
Class cls = Class.forName( "GFG" );
GFG obj = (GFG)cls.newInstance();
System.out.println(obj.name);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (InstantiationException e) {
e.printStackTrace();
}
catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
|
Output:
GeeksForGeeks
Method 3: Using clone() method
Whenever clone() is called on any object, the JVM actually creates a new object and copies all content of the previous object into it. Creating an object using the clone method does not invoke any constructor. In order to use the clone() method on an object we need to implement Cloneable and define the clone() method in it.
Example
Java
class GFG implements Cloneable {
@Override
protected Object clone()
throws CloneNotSupportedException
{
return super .clone();
}
String name = "GeeksForGeeks" ;
public static void main(String[] args)
{
GFG obj1 = new GFG();
try {
GFG obj2 = (GFG)obj1.clone();
System.out.println(obj2.name);
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
|
Note:
- Here we are creating the clone of an existing Object and not any new Object.
- Class need to implement Cloneable Interface otherwise it will throw CloneNotSupportedException.
Method 4: Using deserialization
Whenever we serialize and then deserialize an object, JVM creates a separate object. In deserialization, JVM doesn’t use any constructor to create the object. To deserialize an object we need to implement the Serializable interface in the class.
Example 1
Java
import java.io.*;
class GFG implements Serializable {
private String name;
GFG(String name)
{
this .name = name;
}
public static void main(String[] args)
{
try {
GFG d = new GFG( "GeeksForGeeks" );
FileOutputStream f
= new FileOutputStream( "file.txt" );
ObjectOutputStream oos
= new ObjectOutputStream(f);
oos.writeObject(d);
oos.close();
f.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Output:
GeeksForGeeks
Object of DeserializationExample class is serialized using writeObject() method and written to file.txt file.
Example 2
Java
import java.io.*;
public class GFG {
public static void main(String[] args)
{
try {
GFG d;
FileInputStream f
= new FileInputStream( "file.txt" );
ObjectInputStream oos
= new ObjectInputStream(f);
d = (DeserializationExample)oos.readObject();
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(d.name);
}
}
|
Output:
GeeksForGeeks
Method 5: Using newInstance() method of the constructor class
This is similar to the newInstance() method of a class. There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. It can also call the parameterized constructor, and private constructor by using this newInstance() method. Both newInstance() methods are known as reflective ways to create objects. In fact newInstance() method of Class internally uses newInstance() method of Constructor class.
Example
Java
import java.lang.reflect.*;
class GFG {
private String name;
GFG() {}
public void setName(String name)
{
this .name = name;
}
public static void main(String[] args)
{
try {
Constructor<GFG> constructor
= GFG. class .getDeclaredConstructor();
GFG r = constructor.newInstance();
r.setName( "GeeksForGeeks" );
System.out.println(r.name);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
Output:
GeeksForGeeks
This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.