【问题标题】:Class Instantiation Java [closed]类实例化 Java [关闭]
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • 那么我是否表现得像 A 的超类(父级)?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-03
    • 2016-12-02
    • 1970-01-01
    • 2015-02-08
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多