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.

2. Using Class.forName()

Instead of calling new MyJavaClass(), we can call newInstance() method in this way:

3. Using newInstance() method of Constructor class

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

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.

5. Using Object Deserialization

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

II. Source Code

MyJavaClass.java

MainApp.java

Run the code above, the console shows:

By JavaSampleApproach | February 5, 2017.

Last updated on June 4, 2017.


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*