Narayana Tutorial

Online Java Tutorial Blog

Different ways to create java objects


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.

 

 

Narayanaswamy

Hello! I am Narayanaswamy founder and admin of narayanatutorial.com. I have been working in IT industry more than 7 years. NarayanaTutorial is my web technologies blog. My specialties are Java / J2EE, Spring, Hibernate, Struts, Webservices, PHP, Oracle, MySQL, SQLServer, Web Hosting and Website Development.

I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

The Author

Narayanaswamy

Narayanaswamy

Hello! I am Narayanaswamy founder and admin of narayanatutorial.com. I have been working in IT industry more than 7 years. NarayanaTutorial is my web technologies blog. My specialties are Java / J2EE, Spring, Hibernate, Struts, Webservices, PHP, Oracle, MySQL, SQLServer, Web Hosting and Website Development. I am a self learner and passionate about training and writing. I am always trying my best to share my knowledge through my blog.

Leave a Reply

Narayana Tutorial © 2016 Frontier Theme
Show Button
Hide Button