Site icon Narayana Tutorial

Different ways to create java objects

Classes and Objects interview questions

Different ways to create java objects

In this article we are explaining the various ways to create java objects.

Java Objects can be created in four ways

1) Using new Operator

Employee obj = new Employee();

Here, we are creating Employee class object ‘obj’ using new operator.

2) Using factory methods

NumberFormat obj = NumberFormat.getNumberInstance();

Here, We are creating NumberFormat object using the factory method getNumberInstance();

3) Using newInstance()

Here, we should follow two steps, as

a) First, store the class name ‘Employee’ as a string into object. For this purpose, factory method forName() of the class ‘Class’ will be useful.

Class c = Class.forName(“Employee”);

We should note that there is a class with the name ‘Class’ in java.lang package

b) Next, create another object to the class whose name is in the object c. For this purpose, we need newInstance() method of the class ‘Class’, as

Employee obj = (Employee)c.newInstance();

4) Using Clone() Method

By cloning an already available object, we can create another object. Creating exact copy of an existing object if called ‘cloning’.

Employee obj1 = new Employee();

Employee obj2 = (Employee)obj1.clone();

Earlier, we created obj2 by cloning the Employee object obj1.clone() method of Object class is used to clone an object. We should note that there is a class by the name ‘Object’ in java.lang package.