Different ways of creating object in java

There are different way we can create objects in Java. Let us say i have sample class Test defined as below.

Class Test{
private int count=0;

1.  Using new Operator:
With new operator we are calling default constructor of class to create the Object. Once object is created reference is return back to obj variable.

 Test obj = new Test();

2.Dynamic Class loading:
. In this method object created during the run time dynamically. We are using Class to archive this. Best example for this is database driver class which we used to load during run time.  Class is a class and forName is static method in this class.This method throws class not found exception.


3. Assiging a reference to another variable:
In this method object is created in the first method once object is created we can assign that reference to another variable.

  Test obj = new Test();   Test obj1 = obj;

4. Cloning:
Cloning is an copy of an object,this created one more reference but both the references are pointing to the same object.
   Test obj = new Test();  Test clone = obj.clone();

5. Deserilization:
We can serialize the object by converting into bytes and write using ObjectOutputStream to a file. If we deserialize from file we will be able to retrieve back the object.

ileInputStream fis = new FileInputStream("Test.ser");
ObjectOutputStream ois = new ObjectOutputStream(fis);
Test si = (studentinfo)ois.readObject();
6.Using Reflection:

We can create object using reflection as well. There are two options to create an object using reflection.
  Constructor[] cons = Console.class.getDeclaredConstructors();
Console c = (Console)cons.newInstance();


Post a Comment

Powered by Blogger.