Wednesday, July 13, 2011

Creating Object using keyword “new” & method “newInstance()”

When u use the new operator to create an instance of a class, u cant change the class which is been instantiated. In other words, the class which is instantiated is determined at compile time.


If you use class.newInstance(), then u can change the class which is been instantiated at runtime. In other words for example

Class c = Class.forName("Some class Name");
Object o = c.newInstance();

Here, you can change the String argument in the class.forName() method and change the class which is getting instantiated. Say u got this String from a property file, then u don't even have to compile the class in order to get another different class instantiated.

   1:  package test;
   2:  class Emp {
   3:      String name;
   4:      public String getName() {
   5:          return name;
   6:      }
   7:      public void setName(String name) {
   8:          this.name = name;
   9:      }
  10:  }
  11:  public class Instance {
  12:      public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
  13:          Class c;
  14:          c = Class.forName("test.Emp");
  15:          Emp e = (Emp) c.newInstance();
  16:          Emp emp = Emp.class.newInstance();
  17:          e.setName("Ramesh");
  18:          emp.setName("Krishna");
  19:          System.out.println(e.getName());
  20:          System.out.println(emp.getName());
  21:      }
  22:  }

No comments:

Post a Comment