调用接口类对象与类名称和接口名称之间的区别

时间:2015-04-16 15:45:52

标签: java design-patterns interface

请看以下示例。

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

2 个答案:

答案 0 :(得分:1)

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

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

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

  3. 使用1)优于2)

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

答案 1 :(得分:-1)

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

相关问题