【发布时间】:2012-04-13 12:29:22
【问题描述】:
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(); }
}
谢谢!
【问题讨论】:
-
你能澄清一下问题/问题是什么吗?
标签: java class instantiation