Tuesday, 3 June 2014

How many ways to create an object in java?

        There are four ways to create an object in java(i know).

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.
    e.g     Employee emp=new  Employee();

2) Using Class.forName()
          If we know the name of the class & if it has a public default constructor we
 can create an object in this way.
         Employee ob = (Employee)  
                                        Class..forName("com.adn.Employee").newInstance();

3) Using clone()
       
The clone() can be used to create a copy of an existing object.  
                 Employee emp=new Employee();
                 Employee emp1=emp.clone();

4) Using object deserialization
         Object deserialization is nothing but creating an object from its serialized form.
                ObjectInputStream  inStream = new   
                                                                   ObjectInputStream(anInputStream);
                                     MyObject object = (MyObject) inStream.readObject(); 



 Related post:
Java Object Class and its methods

2 comments:

  1. Thanks Narender. Keep on visiting blog. If you have any queries please comment it.

    ReplyDelete