Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/design-patterns/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用类名和接口名调用接口类对象之间的区别_Java_Design Patterns_Interface - Fatal编程技术网

Java 使用类名和接口名调用接口类对象之间的区别

Java 使用类名和接口名调用接口类对象之间的区别,java,design-patterns,interface,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.printl

请看下面的例子

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

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

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

  • 当你说
    testingthroughinterface=newtestingimplements()时,您正在编程到一个接口

  • 当你说
    TestingImplements directly=newtestingimplements()时,您正在对实现进行编程

  • 使用1)优于2)的优点

  • 编译时优势:您可以在不更改引用的情况下更改get实例化的对象类型,并确保代码将编译。例如,您可以说
    testingthroughinterface=newtestingimplementstwo()并且不需要更改代码的其余部分,因为您知道
    TestingImplementsTwo
    至少包含
    测试中存在的那些方法
  • 运行时优势:您可以通过控制反转在运行时交换实现

  • 这不是一个奇怪的方式,这是首选的方式。您展示的两个示例是相同的(复制+粘贴失败?),感谢您的回答,但稍微细化一下会很好。伙计,您能不能将答案扩展到,使用2)比1)的优点,这样我就可以了解全部情况。使用2比1没有好处。您应该始终使用1。