As you know, in Java, a class provides the blueprint for objects; you create an object from a class. There are four different ways to create objects in java:
Method 1. Using new keyword. This is the most common way to create an object in java. Almost 99% of objects are created in this way.
CrunchifyObj object = new CrunchifyObj();
Method 2. Using Class.forName(). Class.forName() gives you the class object, which is useful for reflection. The methods that this object has are defined by Java, not by the programmer writing the class. They are the same for every class. Calling newInstance() on that gives you an instance of that class (i.e. calling
Class.forName("ExampleClass").newInstance()it is equivalent to calling
new ExampleClass()), on which you can call the methods that the class defines, access the visible fields etc.
CrunchifyObj object2 = (CrunchifyObj) Class.forName("com.crunchify.tutorials.CrunchifyObj").newInstance();
Another must read:
Method 3. Using clone(). The clone() can be used to create a copy of an existing object.
CrunchifyObj secondObject = new CrunchifyObj(); CrunchifyObj object3 = (CrunchifyObj) secondObject.clone();
Method 4. Using Object Deserialization. Object Deserialization is nothing but creating an object from its serialized form.
InputStream inputStream = null; ObjectInputStream inStream = new ObjectInputStream(inputStream); CrunchifyObj object4 = (CrunchifyObj) inStream.readObject();
Complete Example:
package com.crunchify.tutorials; import java.io.InputStream; import java.io.ObjectInputStream; /** * @author Crunchify.com */ public class CrunchifyObj implements Cloneable{ public CrunchifyObj() { System.out.println("Hi!"); } @Override protected Object clone() throws CloneNotSupportedException { return (CrunchifyObj) super.clone(); } @SuppressWarnings("unused") public static void main(String[] args) throws Exception { // Create Object1 CrunchifyObj object1 = new CrunchifyObj(); // Create Object2 CrunchifyObj object2 = (CrunchifyObj) Class.forName("com.crunchify.tutorials.CrunchifyObj").newInstance(); // Create Object3 CrunchifyObj secondObject = new CrunchifyObj(); CrunchifyObj object3 = (CrunchifyObj) secondObject.clone(); // Create Object4 InputStream inputStream = null; ObjectInputStream inStream = new ObjectInputStream(inputStream); CrunchifyObj object4 = (CrunchifyObj) inStream.readObject(); } }
The post What are all the Different Ways to Create an Object in Java?? appeared first on Crunchify.