【问题标题】:Difference Between Calling an interfaced class object with the Class name vs the Interface name使用类名称与接口名称调用接口类对象之间的区别
【发布时间】:2015-04-16 15:45:52
【问题描述】:

请看下面的例子。

public interface Testing {
    public void go();
}

public class TestingImplements implements Testing {
    @Override
    public void go() {

    }
}

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World!");
        Testing throughInterface = new TestingImplements();
        TestingImplements directly = new TestingImplements();
    }
}

我的问题是, 直接使用 throughInterface 有什么优点和缺点。稍微解释一下会很有帮助。

Testing throughInterface = new TestingImplements();

而不是,

TestingImplements directly = new TestingImplements();

【问题讨论】:

  • 这不是奇怪的方式,这是首选方式。
  • 你展示的两个例子是一样的(复制+粘贴失败?)

标签: java design-patterns interface


【解决方案1】:

让我们定义这两种不同方法的含义:

  1. 当您说Testing throughInterface = new TestingImplements(); 时,您正在对接口进行编程。

  2. 当您说TestingImplements directly = new TestingImplements(); 时,您正在对实现进行编程。

使用 1) 优于 2) 的优点

  1. 编译时间优势:您可以在不更改引用的情况下更改实例化对象的类型,并确保代码可以编译。例如,您可以说 Testing throughInterface = new TestingImplementsTwo(); 并且无需更改其余代码,因为您知道 TestingImplementsTwo 将至少包含 Testing 中存在的那些方法
  2. 运行时优势:您可以通过控制反转在运行时交换实现。

【讨论】:

  • 哥们,能否请您将答案扩展到使用 2) 优于 1) 的优点,以便我了解全貌。
  • 使用 2 比 1 没有优势。您应该始终使用 1。
【解决方案2】:

接口的目的是实现多重继承,但是在您的情况下,如果您想更改另一个类中方法的行为,那将很有用。

【讨论】:

  • 感谢您的回答,但稍加阐述会很棒。
猜你喜欢
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2021-06-03
相关资源
最近更新 更多