InstantiationException Exception:当程序试图使用Class类中的newInstance方法创建一个类的实例,而指定的类对象因为是一个接口或是一个抽象类而无法实例化时,抛出该异常。
我们在使用newInstance()实例化对象时,程序经常会抛出InstantiationException Exception,其原因为:
newInstance: 弱类型。低效率。只能调用无参构造。即如果你重写了类的构造函数的话,一定要重写不带参数的构造函数
new: 强类型。相对高效。能调用任何public构造。
newInstance()是实现IOC、反射、依赖倒置 等技术方法的必然选择,new 只能实现具体类的实例化,不适合于接口编程。类里面就是通过这个类的默认构造函数构建了一个对象,如果没有默认构造函数就抛出InstantiationException, 如果没有访问默认构造函数的权限就抛出IllegalAccessException
abstract class Operation {
private double num1;
private double num2;
public double getNum1() {
return num1;
}
public void setNum1(double num1) {
this.num1 = num1;
}
public double getNum2() {
return num2;
}
public void setNum2(double num2) {
this.num2 = num2;
}
public double getResult() {
double result = 0;
return result;
}
}
class OperationAdd extends Operation{
public double getResult() {
double result = 0;
return result = getNum1() + getNum2();
}
}
class OperationSub extends Operation {
public double getResult() {
double result = 0;
return result = getNum1() - getNum2();
}
}
class OperationMul extends Operation {
public double getResult() {
double result = 0;
return result = getNum1() * getNum2();
}
}
class OperationDiv extends Operation {
public double getResult() {
double result = 0;
return result = getNum1() / getNum2();
}
}
class OperationFactory {
public static Operation createOperate(String operate) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Operation oper = null;
switch (operate) {
case "+" :
oper = (OperationAdd.class.newInstance());
break;
case "-" :
oper = (OperationSub.class.newInstance());
break;
case "*" :
oper = (OperationMul.class.newInstance());
break;
case "/" :
oper = (OperationDiv.class.newInstance());
break;
}
return oper;
}
}
/*class OperationFactory {
public static Operation createOperate(String operate) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Operation oper = null;
switch (operate) {
case "+" :
oper = new OperationAdd();
break;
case "-" :
oper = new OperationSub();
break;
case "*" :
oper = new OperationMul();
break;
case "/" :
oper = new OperationDiv();
break;
}
return oper;
}
}*/
public class Calculator {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
Operation oper = OperationFactory.createOperate("/");
oper.setNum1(1);
oper.setNum2(2);
System.out.println(oper.getResult());
}
}