2015-04-16 30 views
-1

请查看以下示例。使用类名称与接口名称调用接口类对象之间的区别

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

这并不奇怪,这是首选的方法。 –

+2

您展示的两个示例是相同的(复制+粘贴失败?) – DaniEll

回答

1

让我们来定义一下两种不同的方法意味着:

  1. 当你说Testing throughInterface = new TestingImplements();,你面向接口编程。

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

超过2用1的优点))

  1. 编译时间上的优势:您可以更改得到真实而不改变参考实例化对象的类型和放心,代码将编译。例如,你可以说Testing throughInterface = new TestingImplementsTwo();和就没有必要改变代码的其余部分,因为你知道一个事实,即TestingImplementsTwo将至少含有一个那些存在于Testing
  2. 运行时间上的优势的方法:你可以换通过控制反转在运行时实现。
+0

好友,请您将答案扩展到使用2)1)以上的优点,以便我可以得到完整的图片。 – blueray

+0

使用2比1更有优势。您应该始终使用1。 – CKing

-1

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

+0

感谢您的答案,但稍微详细一点就会很好。 – blueray

相关问题