大家好,欢迎来到IT知识分享网。
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());
}
}
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/22462.html