Different ways to create an Object in Java

In this post, we will discuss the different ways to create a new Object

Consider we have a class, say CustomClass and we are going to see different ways in which we can create a new object of CustomClass.
  1. Using new keyword/the constructor:
    new CustomClass();
    
  2. Clone
    You already have an object and you using Cloning to create a copy of that object
    CustomClass myObject = new CustomClass();
    CustomClassobject = (CustomClass) myObject.clone();
    
  3. Class.forName:
    The reflection API gives us the ability to create objects without calling the constructor. Spring and Hibernate use reflection to create objects.
    Class.forname(CustomClass);
    

  4. Deserialization is another way of creating the object. First you serialize and then deserialize to get the object.

Comments

Popular posts from this blog

Writing your own ejabberd Module

npm ECONNREFUSED error

Conditional Flow - Spring Batch Part 6