java - 实例化实现接口的类时的对象类型
问题描述
假设我有一个名为 TestClass 的类,它实现了名为 TestInterface 的接口。创建以下对象有什么区别:
TestInterface test1 = new TestClass();
TestClass test2 = new TestClass();
如果没有差异,哪一个是更好的约定?
解决方案
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");
}
}
推荐阅读
- assembly - MIPS Counting Number of 1's given a user input(B 指令不在 MARS 中跳转)
- python - 如何获取 MongoDB 存储的视频文件的剪辑?
- sql - 在 oracle 中编辑请求(添加正确的左侧连接)
- javascript - 在 Vue.js 中调用 AJAX 后重新加载轮播
- excel - 过滤后vba计数可见行
- asp.net-mvc - 返回 RedirectToAction 不起作用
- vue.js - 奇怪的 VueJS 路由行为
- magento - Magento 1.9 - OroCRM 更新同步无法正常工作
- r - 非整数计数的泊松 GLM - R
- viewcontroller - 从另一个 VC 调用 var 的行代码是什么?