Java。如果在方法定义中参数是接口类型,为什么我可以传递对象参数?
Java. Why can i pass an object argument, if in the method definition the arguments are the type of an interface?
假设我有以下界面:
public interface Numeric
{
public Numeric addition(Numeric x,Numeric y);
}
以及以下 class:
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;
}
}
我有几个问题:
加法方法的 return 类型为 Numeric,它的参数
是数字。然后验证 x 和 y 是否属于 Complex 类型。
但是我怎么能传递复杂的参数,当在定义中
参数是数字类型?我return时也一样。我return一个
复杂对象,不是数字。什么是关联和逻辑
这背后.
如果x和y是复杂的,因为我检查了if,为什么我需要将x和y转换为新的2个对象?
如果它们已经很复杂,那么铸造的意义何在。
为什么没有 throw if 就不能工作? UnsupportedOperationException
是什么,为什么它是强制性的?
由于 Complex
实现了 Numeric
,任何 Complex
对象都可以在需要 Numeric
的地方使用。
每个 Numeric
个对象都不是 Complex
。可以有另一个 class Real
其中 Real implements Numeric
。在这种情况下,Numeric
变量可以引用 Real
对象,您不能用 Complex
替换 Real
对象。所以,你需要转换对象。
由于 return 类型的方法 addition
是 Numeric
,您的代码必须 returning 类型 Numeric
的对象.如果您删除 throw 语句并且条件被评估为 false,方法将不会 return 任何东西并且编译器会抱怨。
假设我有以下界面:
public interface Numeric
{
public Numeric addition(Numeric x,Numeric y);
}
以及以下 class:
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;
}
}
我有几个问题:
加法方法的 return 类型为 Numeric,它的参数 是数字。然后验证 x 和 y 是否属于 Complex 类型。 但是我怎么能传递复杂的参数,当在定义中 参数是数字类型?我return时也一样。我return一个 复杂对象,不是数字。什么是关联和逻辑 这背后.
如果x和y是复杂的,因为我检查了if,为什么我需要将x和y转换为新的2个对象? 如果它们已经很复杂,那么铸造的意义何在。
为什么没有 throw if 就不能工作?
UnsupportedOperationException
是什么,为什么它是强制性的?
由于
Complex
实现了Numeric
,任何Complex
对象都可以在需要Numeric
的地方使用。每个
Numeric
个对象都不是Complex
。可以有另一个 classReal
其中Real implements Numeric
。在这种情况下,Numeric
变量可以引用Real
对象,您不能用Complex
替换Real
对象。所以,你需要转换对象。由于 return 类型的方法
addition
是Numeric
,您的代码必须 returning 类型Numeric
的对象.如果您删除 throw 语句并且条件被评估为 false,方法将不会 return 任何东西并且编译器会抱怨。