Java。如果在方法定义中参数是接口的类型,为什么我可以传递对象参数?

问题描述 投票:0回答:1

假设我具有以下界面:

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;
    }
}

我有几个问题:

  1. 加法的返回类型为Numeric,它是参数是数字。然后验证x和y是否为复杂类型。但是当定义中的参数是数字类型的吗?我回来的时候也一样。我返回一个复杂对象,不是数字。什么是相关性和逻辑在此之后。

  2. 如果x和y是Complex,因为我检查了if,为什么需要将x和y强制转换为新的2个对象?如果它们已经很复杂了,那么转换的目的是什么?

  3. 而如果不进行掷球,if为何不起作用? UnsupportedOperationException是什么,为什么它是强制性的?

java oop return arguments throw
1个回答
2
投票
  1. 由于Complex实现了Numeric,因此可以在需要Complex的任何地方使用任何Numeric对象。

  2. 每个Numeric对象都不是Complex。可以有另一个类别Real,其中Real implements Numeric。在这种情况下,Numeric变量可以引用Real对象,并且不能用Real替代Complex对象。因此,您需要转换对象。

  3. 由于方法addition的返回类型为Numeric,因此您的代码必须返回类型为Numeric的对象。如果您删除了throw语句,并且如果condition的计算结果为false,则方法将不返回任何内容,并且编译器将进行投诉。

© www.soinside.com 2019 - 2024. All rights reserved.