- 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(); } }
推薦閱讀
- Mastering Ext JS(Second Edition)
- Programming ArcGIS 10.1 with Python Cookbook
- INSTANT CakePHP Starter
- SAP BusinessObjects Dashboards 4.1 Cookbook
- Mastering Drupal 8 Views
- 飛槳PaddlePaddle深度學(xué)習(xí)實(shí)戰(zhàn)
- Arduino家居安全系統(tǒng)構(gòu)建實(shí)戰(zhàn)
- Spring技術(shù)內(nèi)幕:深入解析Spring架構(gòu)與設(shè)計(jì)原理(第2版)
- Kubernetes進(jìn)階實(shí)戰(zhàn)
- ActionScript 3.0從入門(mén)到精通(視頻實(shí)戰(zhàn)版)
- Training Systems Using Python Statistical Modeling
- Java EE Web應(yīng)用開(kāi)發(fā)基礎(chǔ)
- JavaScript Unit Testing
- Android熱門(mén)應(yīng)用開(kāi)發(fā)詳解
- Access 2016數(shù)據(jù)庫(kù)應(yīng)用與開(kāi)發(fā):實(shí)戰(zhàn)從入門(mén)到精通(視頻教學(xué)版)