How to create object of a Java class?

Java is almost 100% Object Oriented Programming language. Whatever you need to do in Java, you have to create Class. In this post, I am going to tell you how to create the object in java.

Obviously, each object in java will refer to a Class. The most popular and common way of creating an object is by using the new keyword. This is also so simple and easy. It is the most uses way. Below is given an example:

Here is the Java class which is called Persons:

Class Persons {
    // Required code will be here

Below is the code which creates an object of Persons class:

Persons listperson = new Persons();

now the object listperson has been created for Persons Class.

Some other types of example of creating object in Java

Here are some other ways of creating an object for Java class:

Using newInstance() method of Class class

You can also use the newInstance() method of a java Class to create an object of that Class class. Actually, this newInstance() method calls the no-arg constructor to create the object. The newInstance() method can be used in following way:

MyClass emp2 = (MyClass) Class.forName(".codespeedy.MyClass").newInstance();


Using Clone method

When we call clone() method on any one of the object, the JVM actually creates a new object for us and copies all content of a previous object into it. Creating an object using this process does not invoke any constructor.

To use clone() method on an object we need to implement Cloneable and define the clone() method in it. below is the code snippet;

MyJavaObject emp4 = (MyJavaObject) emp3.clone();

Leave a Reply

Your email address will not be published. Required fields are marked *