2012-04-13 185 views
-4
I i = new A(); 

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

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

谢谢!

+5

你能否澄清问题是什么? – beny23 2012-04-13 12:32:29

回答

3

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

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

A完成接口I指定的一切,因此它与参考的声明类型I兼容。通过接口和继承,对象可以有多种类型。

+0

那么,我是否像A的超类(父)一样行事? – 2012-04-13 17:19:04

1

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

+0

谢谢!我现在明白了 – 2012-04-13 17:23:05