Java.如果在方法定义中参数是接口的类型,为什么要传递对象参数? [英] Java. Why can i pass an object argument, if in the method definition the arguments are the type of an interface?

查看:507
本文介绍了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;
    }
}

我有几个问题:

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

  1. The addition method has the return type Numeric, and it's arguments are Numeric. x and y are then verified if they are of type Complex. But how can I pass Complex arguments, when in the definition the arguments are of type Numeric? The same when I return. I return a Complex object, not Numeric. What is the correlation and logic behind this.

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

If x and y are Complex, because I checked in the if, why do I need to cast x and y to new 2 objects? What is the point of casting, if they are already Complex.

那为什么if如果没有抛出就无法工作呢? UnsupportedOperationException是什么,为什么是强制性的?

And why the if doesn't work without the throw? What does UnsupportedOperationException is, and why is it mandatory?

推荐答案

  1. 由于Complex实现了Numeric,因此可以在需要Numeric的任何地方使用任何Complex对象.

  1. As Complex implements Numeric, any Complex object can be used wherever Numeric is expected.

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

Every Numeric object is not Complex. There can be another class Real where Real implements Numeric. In this case, a Numeric variable can be referencing a Real object and you cannot substitute a Real object with Complex. So, you need to cast the object.

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

As return type of method addition is Numeric, your code MUST be returning an object of type Numeric. In case you remove throw statement and if condition is evaluated to false, method will not return anything and compiler will complain.

这篇关于Java.如果在方法定义中参数是接口的类型,为什么要传递对象参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆