Different Ways of Creating Object in java

Connect with

Oracle Java
This question generally ask in the interview to check the basic of core java. In real life purpose of all the type of creating object are different. Usually when we required a object to call their function/method , we use new operator , it means , when we call new Claszz() it invoke default constructor.

There are four different ways to create objects in java

  1. . Using new keyword
  2. This is the most common way to create an object in java, when we required to access any method on it. You can say, approx 99% of objects are created via this way.

    
     MyClazz myClazz = new MyClazz();
    
    
  3. Using Class.forName()
  4. Question is why we required to create an object using Class.forName(), usually if class is not loaded in our jvm, and you want to load at run time, any third party class, from third party jar file, we should go for this way. If we know the name of the class and if it has a public default constructor we can create an object in this way.

     
    MyClazz object = (MyClazz) Class.forName("com.mysoftkey.MyClazz").newInstance();
    
    
  5. Using clone()
  6. The clone() can be used to create a copy of an existing object. there are 2 different variant of it , shallow copy and deep copy of it. usually use this in prototype design creational design pattern.

    
    MyClazz myClazz = new MyClazz();
    MyClazz anotherObject = (MyClazz) myClazz.clone();
    
    
  7. Using object Deserialization
  8. Object deserialization is nothing but creating an object from its serialized form.

    
    ObjectInputStream inStream = new ObjectInputStream(anInputStream );
    MyClazz object = (MyClazz) inStream.readObject();
    
    

    Now you know how to create an object. Preference is yours choice but be careful how to create and what scenario we choose what option.

    If any suggestion please write comment , will modify accordingly.


    Connect with

1 thought on “Different Ways of Creating Object in java

Leave a Reply

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