首页 > 解决方案 > 实例化实现接口的类时的对象类型

问题描述

假设我有一个名为 TestClass 的类,它实现了名为 TestInterface 的接口。创建以下对象有什么区别:

TestInterface test1 = new TestClass();
TestClass test2 = new TestClass();

如果没有差异,哪一个是更好的约定?

标签: java

解决方案


interface TestInterface {
    public void function2();
}

public class TestClass implements TestInterface {
    public static void main(String... args) {
        TestInterface testInterface = new TestClass();
        TestClass testClass = new TestClass();

        /* function1 belongs to TestClass class only */
        testInterface.function1(); // This gives you compile time error as function1 doesn't belong to TestInterface
        testClass.function1(); // Whereas this is ok.

        /* function2 belongs to TestInterface and TestClass, so function2 can be called from both object (testClass and testInterface) */
        testInterface.function2(); 
        testClass.function2();
    }
    public void function1() {
        System.out.println("This is function 1");
    }
    public void function2() {
        System.out.println("This is function 2");
    }
}

推荐阅读