Wednesday, March 13, 2013

different ways to create an object in Java

There are 4 ways of creating objects in Java.

1. Using new operator

Employee emp = new Employee();

Here , we are creating Employee class object  'emp' using new operator.

2. Using factrory methods:

NumberFormat nf  = NumberFormat.getNumberInstace();

Here, we are creatig NumberFormat object using the factory method getNumberInstacne().

3. Using newInstance() method .

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

Class c = Class.forName("Employee");

Note: class with the name 'Class' in java.lang package.
(b) 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. By cloning an already available object, we can create another object . Creating exact copy of an
existing object is called 'cloning':

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

1 comment: