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

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(); } }

主站蜘蛛池模板: 集贤县| 禄丰县| 汤原县| 桂阳县| 东安县| 焉耆| 岳普湖县| 阿克陶县| 巴东县| 朝阳市| 双柏县| 凌源市| 翁源县| 长阳| 新化县| 玛纳斯县| 桐庐县| 临潭县| 桐庐县| 江西省| 阿坝县| 松滋市| 天水市| 普兰店市| 宁陵县| 巴南区| 三亚市| 甘谷县| 阿拉尔市| 澜沧| 阿拉善左旗| 郑州市| 广饶县| 邹城市| 任丘市| 宁海县| 甘谷县| 隆安县| 江孜县| 新津县| 南安市|