- 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(); } }
推薦閱讀
- Python概率統(tǒng)計
- JavaScript修煉之道
- Web交互界面設計與制作(微課版)
- Vue.js 3.x從入門到精通(視頻教學版)
- HTML5+CSS3基礎開發(fā)教程(第2版)
- Learning Salesforce Einstein
- OpenGL Data Visualization Cookbook
- UNIX Linux程序設計教程
- R數據科學實戰(zhàn):工具詳解與案例分析
- 快速入門與進階:Creo 4·0全實例精講
- CRYENGINE Game Development Blueprints
- Practical Predictive Analytics
- JavaScript編程精解(原書第2版)
- 例說FPGA:可直接用于工程項目的第一手經驗
- INSTANT Lift Web Applications How-to