[英]Type of object while instantiating a class that implements interface
Let's say I have a class named TestClass that implements interface named TestInterface.假设我有一个名为 TestClass 的 class 实现名为 TestInterface 的接口。 What is the difference in creating following objects:
创建以下对象有什么区别:
TestInterface test1 = new TestClass();
TestClass test2 = new TestClass();
If there is no differences, which one is the better convention?如果没有差异,哪一个是更好的约定?
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");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.