- Java 11 and 12:New Features
- Mala Gupta
- 236字
- 2021-07-02 12:27:00
Passing inferred variables to a method
Though the use of var is limited to the declaration of local variables, these variables (both primitive and reference) can be passed to methods as values. The inferred types and the types expected by the methods must match, to allow the code to compile.
In the following example code, the Child class implements the MarathonRunner interface. The start() method in the Marathon class expects the MarathonRunner object (the instances of the class implementing this interface) as its method argument. The inferred type of the aRunner variable is Child. Since the Child class implements MarathonRunner, aRunner can be passed to the start() method, the inferred type of aRunner (Child) and the expected type of start() (MarathonRunner) match, allowing the code to compile.
The code is 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"); } } class Marathon { public static void main(String[] args) { var aRunner = new Child(); // Inferred type is Child start(aRunner); // ok to pass it to method start
// (param - MarathonRunner) } public static void start(MarathonRunner runner) { runner.run(); } }
- 工程軟件開發(fā)技術(shù)基礎(chǔ)
- 移動UI設(shè)計(微課版)
- 跟小海龜學(xué)Python
- Java 9 Programming Blueprints
- ASP.NET Core 2 and Vue.js
- Mastering C# Concurrency
- SQL基礎(chǔ)教程(視頻教學(xué)版)
- Flutter跨平臺開發(fā)入門與實戰(zhàn)
- Learning ArcGIS for Desktop
- 小程序,巧應(yīng)用:微信小程序開發(fā)實戰(zhàn)(第2版)
- GameMaker Essentials
- Modern C++ Programming Cookbook
- Visual C++程序設(shè)計與項目實踐
- PHP項目開發(fā)全程實錄(第4版)
- 零基礎(chǔ)學(xué)Java(第5版)