We have one method newInstace() on java.lang.class to create object of a class.
Here newInstance() method will call no argument constructor and this no argument constructor can make call to any other constructor. Hence creating object using new keyword i.e using constructor is preferred.
Syntax: public T newInstance() throws InstantiationException, IllegalAccessException
package com.sample.java.testing;
public class NewInstanceDemo {
int i = 10;
public NewInstanceDemo() {
this(10);
System.out.println("no arg con calld using newInstance");
}
public NewInstanceDemo(int k, int h) {
System.out.println("two arg con calld using newInstance");
}
public NewInstanceDemo(int k) {
this(10, 8);
System.out.println("one arg con calld using newInstance");
}
public String getMessage() {
return "using newInstance() method";
}
public static void main(String[] args){
}
}
package com.sample.java.testing;
public class NewInstanceTest {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Class class2 = NewInstanceDemo.class;
NewInstanceDemo newInstanceDemo = (NewInstanceDemo) class2.newInstance();// creating object of class ReflectionTest
System.out.println(newInstanceDemo.getMessage());
}
}
Output:
two arg con calld using newInstance
one arg con calld using newInstance
no arg con calld using newInstance
using newInstance() method
Here newInstance() method will call no argument constructor and this no argument constructor can make call to any other constructor. Hence creating object using new keyword i.e using constructor is preferred.
Syntax: public T newInstance() throws InstantiationException, IllegalAccessException
package com.sample.java.testing;
public class NewInstanceDemo {
int i = 10;
public NewInstanceDemo() {
this(10);
System.out.println("no arg con calld using newInstance");
}
public NewInstanceDemo(int k, int h) {
System.out.println("two arg con calld using newInstance");
}
public NewInstanceDemo(int k) {
this(10, 8);
System.out.println("one arg con calld using newInstance");
}
public String getMessage() {
return "using newInstance() method";
}
public static void main(String[] args){
}
}
package com.sample.java.testing;
public class NewInstanceTest {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Class class2 = NewInstanceDemo.class;
NewInstanceDemo newInstanceDemo = (NewInstanceDemo) class2.newInstance();// creating object of class ReflectionTest
System.out.println(newInstanceDemo.getMessage());
}
}
Output:
two arg con calld using newInstance
one arg con calld using newInstance
no arg con calld using newInstance
using newInstance() method
No comments:
Post a Comment