类实例化Java

时间:2012-04-13 12:29:22

标签: java class instantiation

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

谢谢!

2 个答案:

答案 0 :(得分:3)

  

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

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

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

答案 1 :(得分:1)

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

相关问题