具有接口返回类型的方法,该方法返回实现接口的实例

时间:2019-05-02 21:08:01

标签: java methods interface return implements

假设您有一个界面:

public interface InstanceInterface {
    public int getNumber();
}

并且有一个实现此接口的类:

public class Instance implements InstanceInterface {
    int number;
    public Instance(int number) {
        this.number = number;
    }

    @Override
    public int getNumber {
        return this.number;
    }
}

假设另一个类具有返回类型为InstanceInterface的方法,并假定此方法创建了Instance的实例并返回此值:

public class Example {
    public InstanceInterface returnInstance() {
        Instance instance = new Instance(12345);
        return instance;
    }
}

当方法指定类型必须为Instance时,为什么允许这里返回类型为InstanceInterface的东西?这到底是什么意思?为什么这样有用?

0 个答案:

没有答案
相关问题