官术网_书友最值得收藏!

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(); } }
As long as the inferred type of a variable matches the type of the method parameter, it can be passed to it as an argument.
主站蜘蛛池模板: 尤溪县| 大埔区| 林州市| 安远县| 屯门区| 太仆寺旗| 东乡| 江山市| 开鲁县| 苏尼特右旗| 成武县| 墨竹工卡县| 兴安盟| 抚远县| 鱼台县| 罗江县| 和田市| 嘉峪关市| 临泽县| 海晏县| 凤翔县| 若尔盖县| 金堂县| 济阳县| 乳山市| 双辽市| 凉城县| 霸州市| 辛集市| 荥经县| 余姚市| 大丰市| 曲麻莱县| 合山市| 玉田县| 都匀市| 平顶山市| 临江市| 伊金霍洛旗| 开江县| 阳曲县|