方法一:利用 Wrapper Class Integer
public class B {
public int add(int i, int j) {
return 0;
}
public int add(Integer i, Integer j) throws Exception {
return 0;
}
}
方法2:使用覆盖
您可以利用overriding method can choose not to throw exception at all.
您可以做的是声明一个Parent类,该类将具有方法exception和child类,该类does not have the exception将覆盖父类的方法。现在,当您希望客户端使用add异常时,请使用 typeA传递引用,否则使用 type 传递引用B:
class A { // <---New Class
public int add(int i, int j) throws Exception { // <-- Method with Exception
return 0;
}
}
class B extends A { // <----Original Class
@Override
public int add(int i, int j) { // <--- Original Method
return 0;
}
}