Create Class Instance in Java

Creating class instances in Java is a fundamental concept in object-oriented programming. A class is a blueprint for creating objects, and an object is an instance of a class. In this blog post, we will learn how to create a class instance in Java and understand the various ways in which it can be done.

There are several ways to create class instances in Java:

  1. Using the new keyword
  2. Using the clone() method
  3. Using the Class.forName()

Create a class instance using the new keyword

Using the new keyword: This is the most common way to create an instance of a class in Java. It involves using the new keyword followed by the constructor of the class.

For example:

public class MyClass {
   public MyClass() {
      // constructor code here
   }
}

// Creating an instance of MyClass
MyClass myObj = new MyClass();

Create a class instance using the clone() method

Using the clone() method: The clone() method is a method in the Object class that creates a copy of an object. It is defined as:

protected Object clone() throws CloneNotSupportedException

To use the clone() method, the class must implement the Cloneable interface, which is a marker interface (an interface with no methods). If the class does not implement the Cloneable interface, then calling the clone() method will throw a CloneNotSupportedException.

Let’s see an example of creating a class instance using the clone() method:

public class MyClass implements Cloneable {
   int x;
   String y;

   public MyClass(int x, String y) {
      this.x = x;
      this.y = y;
   }

   public Object clone() throws CloneNotSupportedException {
      return super.clone();
   }
}

// Creating an instance of MyClass
MyClass obj1 = new MyClass(10, "hello");

// Cloning obj1 to create a new instance
MyClass obj2 = (MyClass) obj1.clone();

Create a class instance using the Class.forName() method

Using the Class.forName() method: This method is used to load a class at runtime. It takes a string parameter representing the fully qualified class name (including the package name) and returns the Class object associated with that class. We can then use the newInstance() method of the Class object to create an instance of the class.

Let’s see an example to create a class instance using the Class.forName() method:

try {
   // Load the class at runtime
   Class cls = Class.forName("com.example.MyClass");

   // Create an instance of the class
   Object obj = cls.newInstance();
} catch (ClassNotFoundException e) {
   // Class not found
} catch (InstantiationException e) {
   // Class is an interface or abstract class
} catch (IllegalAccessException e) {
   // Class cannot be accessed (e.g. due to lack of access modifiers)
}

These are the three main ways to create class instances in Java. It is important to understand how each of these methods works and when to use them in order to effectively use object-oriented programming in Java.