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

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

主站蜘蛛池模板: 寿阳县| 清镇市| 吕梁市| 威远县| 山东省| 海晏县| 会宁县| 崇信县| 山东省| 开江县| 虹口区| 三亚市| 大关县| 泰州市| 华宁县| 辉南县| 湖口县| 博乐市| 长垣县| 青海省| 贡觉县| 科技| 五大连池市| 抚州市| 黄骅市| 石柱| 沙坪坝区| 育儿| 板桥市| 合阳县| 阳朔县| 潍坊市| 招远市| 温泉县| 美姑县| 西青区| 江口县| 兰考县| 盐池县| 广汉市| 正阳县|