-4
I i = new A();

为什么我们可以使用接口 I 来实例化类 A 的对象?我们不应该使用 A obj=new A() 吗?

interface I {
    void f();
    void g();
}

class A implements I {
    public void f() { System.out.println("A: doing f()"); }
    public void g() { System.out.println("A: doing g()"); }
}

class B implements I {
    public void f() { System.out.println("B: doing f()"); }
    public void g() { System.out.println("B: doing g()"); }
}

class C implements I {
// delegation
    I i = new A();

    public void f() { i.f(); }
    public void g() { i.g(); }

    // normal attributes
    public void toA() { i = new A(); }
    public void toB() { i = new B(); }
}

谢谢!

4

2 回答 2

3

我们如何使用“I”类型的引用变量来引用“A”类型的对象?

因为A implements I(从您的代码中逐字引用)。

A执行 interface 指定的所有操作I,因此它与引用的声明类型兼容I。通过接口和继承,对象可以有多种类型。

于 2012-04-13T12:32:16.857 回答
1

这是因为 A 是 I 类型,因为它实现了 I 接口。

于 2012-04-13T12:32:26.690 回答