首页 > 解决方案 > 爪哇。如果在方法定义中参数是接口的类型,为什么我可以传递对象参数?

问题描述

假设我有以下界面:

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,它的参数是 Numeric。然后验证 x 和 y 是否属于 Complex 类型。但是,当定义中的参数是数字类型时,如何传递复杂参数?我回来的时候也是这样。我返回一个复杂对象,而不是数字。这背后的关联和逻辑是什么。

  2. 如果 x 和 y 是复杂的,因为我签入了 if,为什么我需要将 x 和 y 强制转换为新的 2 个对象?如果它们已经很复杂,那么铸造的意义何在。

  3. 为什么如果没有 throw 则 if 不起作用?什么UnsupportedOperationException是,为什么是强制性的?

标签: javaoopreturnargumentsthrow

解决方案


  1. 作为Compleximplements Numeric,任何Complex对象都可以在任何需要的地方使用Numeric

  2. 每个Numeric对象都不是Complex。可以有另一个类Real在哪里Real implements Numeric。在这种情况下,一个Numeric变量可以引用一个Real对象,您不能RealComplex. 因此,您需要投射对象。

  3. 由于方法的返回类型additionNumeric,您的代码必须返回类型的对象Numeric。如果您删除 throw 语句并且如果条件被评估为 false,则方法将不会返回任何内容并且编译器会抱怨。


推荐阅读