https://grokonez.com/java/ways-to-create-a-java-object

Ways to create a Java Object

Object is an important concept in Java Development. This tutorial shows you the ways to create a Java Object.

I. Ways to create a Java Object

1. Using 'new' keyword

This is the most popular way to create an object.
MyJavaClass object = new MyJavaClass();

2. Using Class.forName()

Instead of calling new MyJavaClass(), we can call newInstance() method in this way:
MyJavaClass object = (MyJavaClass) Class.forName("com.javasampleapproach.createobject.MyJavaClass").newInstance();

3. Using newInstance() method of Constructor class

java.lang.reflect.Constructor class has newInstance() method which can be used to create objects.

Constructor constructor = MyJavaClass.class.getConstructor();
MyJavaClass object = constructor.newInstance();

4. Using clone() method

There will be no constructor to be invoked when using clone() method, the JVM generates exactly the object which content is the same as content of the object which call the method.

// we should implement Cloneable and define the clone() method before
MyJavaClass object2 = (MyJavaClass) object1.clone();

5. Using Object Deserialization

This way creates an object from its serialized form. We should implement a Serializable interface in the class before.

More at:

https://grokonez.com/java/ways-to-create-a-java-object

Ways to create a Java Object

#java #object

Ways to create a Java Object » grokonez
1.10 GEEK