Saturday, November 28, 2015

Instantiate Object without using new Operator

1) Using newInstance() and Class method

forName() is a static method of java.lang.Class that loads the .class file of CreateObject into the RAM and returns the Hello as an object of class Class. c1 contains the reference of CreateObject .newInstance() method of class Class returns an object of Object class. Now, obj1 contains the reference of Hello. Internally, JVM may use new keyword.

public class CreateObject {

     public void Test() {
           System.out.println("Calling Function");
     }

     public static void main(String[] argsthrows ClassNotFoundException,Instantiat  ionException, IllegalAccessException {
          
           // Overloaded Class.forName(className, true, currentLoader)
           Class ref = Class.forName("com.javaetutorials.CreateObject");
          

Class.forName() loads the class in memory. To create an instance of this class, we need to use newInstance(). A call to forName("X") causes the class named X to be initialized.
          
Parameters: className -the fully qualified name of the desired class.
          Returns: the Class object for the class with the                     specified name.
          
CreateObject co = (CreateObject) ref.newInstance();
          
* Returns: a newly allocated instance of the class represented by this object.
           co.Test();
     }
}


2) Using Cloneable Interface

 In cloning, object to object is assigned, but at the same time encapsulation is maintained. Both objects occupy two different locations; that is, cloning creates a duplicate object which is no way connected with the original one.
Cloning – interface Cloneable and clone() method
In cloning, the interface Cloneable and method clone() of Object class are used. To clone an object, the class should implement Cloneable interface; else, the JVM throws a checked exception, CloneNotSupportedException.

Following are the requirements for cloning.
1.   Implement Cloneable interface
2.   Use clone() method of Object class
3.   After cloning, explicit casting is required

Array Cloning

Arrays are predefined objects in the Java language itself. So, like any other object, arrays also can be cloned. Following program illustrates.

 public class CreateObjectClone implements Cloneable {
     int salary;

     public static void main(String args[]) {
           CreateObjectClone work1 = new CreateObjectClone();
           work1.salary = 3000;

           try {
                CreateObjectClone work2 = (CreateObjectClone)                       work1.clone();

                System.out.println("After cloning, work2 salary: " +                 work2.salary); // 3000
                work1.salary = 4000; // change work1 salary
                System.out.println("After changing work1 salary,                     work2 salary: " work2.salary); // 3000

                work2.salary = 5000; // now change work2 salary
                System.out.println("After changing work2 salary,                     work1 salary: "  + work1.salary); // 4000
                
                // let us see the hash codes
                System.out.println("Hash code of work1: " +                         work1.hashCode());
                System.out.println("Hash code of work2: " +                         work2.hashCode());
           } catch (CloneNotSupportedException e) {
                System.out.println("Check your class implemented                     Cloneable interface. "e);
           }
     }
}

Output:

After cloning, work2 salary: 3000
After changing work1 salary, work2 salary: 3000
After changing work2 salary, work1 salary: 4000
Hash code of work1: 954599881

Hash code of work2: 109873230

class ArrayClone {
     public static void main(String args[]) {
           int x1[] = { 10, 29, 30, 40 };
           int x2[] = x1.clone();

           System.out.println(x2[0]); // prints 10
           // now changing x1 value does not affect x2
           x1[0] = 100;
           System.out.println(x2[0]); // printgs same 10
     }
}



3) Using java.lang.ClassLoader

forName is a static method of Class Class. It'll load and initialize Demo class in RAM


public class Demo
{
  int x = 10;
  public static void main(String args[]) throws Exception
  {    
    Class cls = Class.forName("Demo");
    System.out.println(cls);
    ClassLoader cLoader = cls.getClassLoader();
    System.out.println(cLoader);
     Class cl = cLoader.loadClass("Demo");

    Demo d1 =(Demo) cl.newInstance();                                                          
    System.out.println(d1.x);                              // prints 10
  }
}

Output:

class com.javaetutorials.Demo
sun.misc.Launcher$AppClassLoader@221a5d08

No comments:

Post a Comment