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

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

主站蜘蛛池模板: 双柏县| 郁南县| 平江县| 井研县| 梧州市| 许昌县| 乌拉特前旗| 乳山市| 镇原县| 大邑县| 晋中市| 三亚市| 拉萨市| 壶关县| 慈溪市| 凯里市| 东乡族自治县| 武陟县| 隆回县| 会宁县| 四平市| 阜阳市| 绥滨县| 陆良县| 文山县| 普安县| 景谷| 阿勒泰市| 通辽市| 鄂伦春自治旗| 尚志市| 磐石市| 大名县| 江津市| 宜阳县| 江阴市| 东乌珠穆沁旗| 鹿泉市| 安多县| 临清市| 隆尧县|