java - 爪哇。如果在方法定义中参数是接口的类型,为什么我可以传递对象参数?
问题描述
假设我有以下界面:
public interface Numeric
{
public Numeric addition(Numeric x,Numeric y);
}
以及以下课程:
public class Complex implements Numeric
{
private int real;
private int img;
public Complex(int real, int img){
this.real = real;
this.img = img;
}
public Numeric addition(Numeric x, Numeric y){
if (x instanceof Complex && y instanceof Complex){
Complex n1 = (Complex)x;
Complex n2 = (Complex)y;
return new Complex(n1.getReal() + n1.getReal(), n2.getImg() +
n2.getImg());
} throw new UnsupportedOperationException();
}
public int getReal(){
return real;
}
public int getImg(){
return img;
}
}
我有几个问题:
加法方法的返回类型为 Numeric,它的参数是 Numeric。然后验证 x 和 y 是否属于 Complex 类型。但是,当定义中的参数是数字类型时,如何传递复杂参数?我回来的时候也是这样。我返回一个复杂对象,而不是数字。这背后的关联和逻辑是什么。
如果 x 和 y 是复杂的,因为我签入了 if,为什么我需要将 x 和 y 强制转换为新的 2 个对象?如果它们已经很复杂,那么铸造的意义何在。
为什么如果没有 throw 则 if 不起作用?什么
UnsupportedOperationException
是,为什么是强制性的?
解决方案
作为
Complex
implementsNumeric
,任何Complex
对象都可以在任何需要的地方使用Numeric
。每个
Numeric
对象都不是Complex
。可以有另一个类Real
在哪里Real implements Numeric
。在这种情况下,一个Numeric
变量可以引用一个Real
对象,您不能Real
用Complex
. 因此,您需要投射对象。由于方法的返回类型
addition
是Numeric
,您的代码必须返回类型的对象Numeric
。如果您删除 throw 语句并且如果条件被评估为 false,则方法将不会返回任何内容并且编译器会抱怨。
推荐阅读
- javascript - XMLHttpRequest:网络错误 0x2eff,在 IE 11 中发出 POST 请求时由于错误 00002eff 错误而无法完成操作
- postgresql - 无法投射 ltree JPARepository
- r - R将分组变量的向量传递给purrr :: map
- python - Matplotlib 在 python 中的非对称误差线绘图
- apache-spark - 如何检查 Dataproc 上 pyspark 作业的每个执行程序/节点内存使用指标?
- r - R正则表达式提取独立字符
- php - 多维搜索未显示所有结果
- javascript - 用户密钥通过域名身份验证后如何添加 JavaScript 代码
- azure - 带有基本 SKU 的 Azure 点到站点 VPN 无法在 Windows 10 上运行(错误代码 = 720 错误源 = RAS)
- validation - swagger 的服务器端验证