- Java 11 and 12:New Features
- Mala Gupta
- 169字
- 2021-07-02 12:26:59
Type inference with interfaces
Let's extend the content of the preceding section to the use of interfaces. Imagine that the Child class implements a MarathonRunner interface, as follows:
interface MarathonRunner{ default void run() { System.out.println("I'm a marathon runner"); } } class Child implements MarathonRunner { void whistle() { System.out.println("Child-Whistle"); } void stand() { System.out.println("Child-stand"); } }
Let's define an obj local variable, assigning it an instance of the Child class:
class Test{ public static void main(String[] args) { var obj = new Child(); // inferred type of var obj
// is Child obj.whistle(); obj.stand(); obj.run(); } }
If the same variable is initialized using a method whose return type is MarathonRunner, its inferred type is MarathonRunner (irrespective of the type of the instance returned by it):
class Test{ public static MarathonRunner getObject() { return new Child(); } public static void main(String[] args) { var obj = getObject(); // inferred type of var obj is
// MarathonRunner obj.whistle(); obj.stand(); obj.run(); } }
推薦閱讀
- 編程的修煉
- Windows系統(tǒng)管理與服務配置
- Java 11 Cookbook
- Visual FoxPro程序設計
- Learning OpenStack Networking(Neutron)
- Python機器學習算法: 原理、實現(xiàn)與案例
- 計算機應用基礎教程(Windows 7+Office 2010)
- 軟件項目管理實用教程
- Hands-On GUI Programming with C++ and Qt5
- Web Developer's Reference Guide
- 區(qū)塊鏈架構(gòu)之美:從比特幣、以太坊、超級賬本看區(qū)塊鏈架構(gòu)設計
- Docker:容器與容器云(第2版)
- 軟件測試技術
- HTML5 WebSocket權(quán)威指南
- 和孩子一起學編程:用Scratch玩Minecraft我的世界