Saturday, May 11, 2013

How many ways to create object for java class

                        If you want to create object for java class, generally our program has new keyword and constructor or default constructor.But we can create object in & ways.These are 
1. By using new keyword

2.By using newInstance() method

3.By using static factory method

4.By using instance factory method

5.By using factory pattern

6.By using cloning process

7.By using Deserilization

1.By using new keyword:
              We can create object for java class by using new keyword.It is a normal process.
  Example:
            String name=new String("RRV");
            Test t=new Test();

2. By using newInstance() method:
     
          We can create object for java class by using newInstance() method.Generally we can use new keyword for creating object but it checking java class at compile time that's why it is not useful in jdbc applications and other applications which taking java class files dynamically.For that purpose we use newInstance() method.

Example:
           Class c=Class.forName("Sun.jdbc.odbc.JdbcOdbcDriver");
        JdbcOdbcDriver jod=(JdbcOdbcDriver)c.newInstance();

3. By using static factory method:
                Method of a java class that is capable of constructing and returing its own java class object is called as Static factory method.

Example: 
      Thread t=Thread.currentThread();
      Class.forName("Sun.jdbc.odbc.JdbcOdbcDriver");

Note:
         When java class contains only private constructors to create object of that class outside the class we take support od\f static factory method.
          Inabove  java.lang.Class is having only Private Constructor so we always use Class.forName() method as shown above create the object.

4.By using instance factory method:
                  In order to create a new object  for java class by using existing object and its data.

Example:
           String name=new String("RRV");
           String name1=name.concat("TechDiamond");

      In above example concat() method is using object "name" and its data while constructing "name1" object.

5. By using factory pattern:
             If method of one java class is returing object of other java class then it is called as Factory Pattern.

Example:
    StringBuffer name=new StringBuffer("RRVTechDiamond");
    String s=name.subString(6,3);
If method one java class wants to return another java class object then these both classes need not to be there in inheritance relationship.If they are visible to each other.

6.By using cloning process:
              The process of creating object of a java class having existing object data is called as cloning process.We can perform cloning only on clonable objects.
                                      
7.By using Deserialization process:
                  The process of reading data from a file and constructing new object having that data is called as Deserialization.





















1 comment: