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

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.
主站蜘蛛池模板: 嘉祥县| 兴业县| 浦北县| 博乐市| 科尔| 杭锦旗| 东阿县| 临武县| 成武县| 大理市| 肃宁县| 探索| 增城市| 安仁县| 巴青县| 乌拉特后旗| 张家港市| 井研县| 宁德市| 衢州市| 天门市| 余庆县| 抚远县| 涿鹿县| 鄂尔多斯市| 江北区| 沂源县| 通辽市| 洱源县| 天水市| 安图县| 庄河市| 江口县| 溧水县| 深水埗区| 万宁市| 宜城市| 江陵县| 扎兰屯市| 虎林市| 陆良县|