Welcome to my blog, hope you enjoy reading

Monday, 15 April 2013

How many ways to create object in java?

How many ways to create object in java?

There are different ways to create object in java as follows:--

1. Using new keyword
we can create the instance normally using new operator which is called as static instance creation.
Hello hello =  new Hello();

2.using Class.forName()
we can create the instance dynamically without using new operator as follow
Hello hello=(Hello)Class.forName("com.bikash.Hello").newInstance();
Class cls = Class.forName("com.bikash.Hello");
Hello hello = (Hello)cls.newInstance();

3.using clone().
clone() method can be used to copy of the existing object.
Hello hello=new Hello();
Hello hello1=(Hello)hello.clone();

4.using object deserialization.
deserializion is the process of creating the new object on the remote mechine from its serialize form.
ObjectInputStream ois =new ObjectInputStream();
Hello hello = (Hello)ois.readObject();