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

Type inference with derived classes

In JDK 9 and other previous versions, you could define a variable of the base class and assign an instance of its derived class to it. The members that you could access using the variable were limited to the ones that were defined in the base class. This is no longer the case with var, since the type of the variable is inferred by using the specific type of the instance that is assigned to it.

Imagine a class  Child extends a class Parent. When you create a local variable and assign it an instance of the Child class, the type of the variable is inferred as Child. This looks simple. The following is an example:

class Parent { 
    void whistle() { 
        System.out.println("Parent-Whistle"); 
    } 
} 
class Child extends Parent { 
    void whistle() { 
        System.out.println("Child-Whistle"); 
    } 
    void stand() { 
        System.out.println("Child-stand"); 
    } 
} 
class Test{ 
    public static void main(String[] args) { 
        var obj = new Child();                             
        obj.whistle(); 
        obj.stand();     // type of obj inferred as Child 
    } 
}

What happens if you assign the value of the obj variable using a method that can return an instance of the Child class or Parent classes? Here's the modified code:

class Parent { 
    void whistle() { 
        System.out.println("Parent-Whistle"); 
    } 
} 
 
class Child extends Parent { 
    void whistle() { 
        System.out.println("Child-Whistle"); 
    } 
    void stand() { 
        System.out.println("Child-stand"); 
    } 
} 
 
class Test{ 
    public static Parent getObject(String type) { 
        if (type.equals("Parent")) 
            return new Parent(); 
        else 
            return new Child(); 
    } 
 
    public static void main(String[] args) { 
        var obj = getObject("Child"); 
        obj.whistle(); 
        obj.stand();              // This line doesn't compile 
    } 
} 

In the preceding code, the type of the instance returned by the getObject() method can't be determined before the code execution. During compilation, the type of the obj variable is inferred as Parent, the return type of the getObject() method. Since the Parent class doesn't define stand(), the main() methods fail to compile.

The types of variables defined using var are inferred at compile time. If the return type of a method is used to assign a variable that is defined using var, its inferred type is the return type of the method, not the type of the instance returned during runtime.
主站蜘蛛池模板: 桦川县| 乌兰浩特市| 扎赉特旗| 梓潼县| 孝昌县| 汝州市| 洪泽县| 镇原县| 辽中县| 临城县| 诸暨市| 平顶山市| 阳高县| 满洲里市| 班戈县| 固原市| 从江县| 渭源县| 长沙县| 南康市| 伽师县| 磴口县| 罗源县| 房产| 池州市| 长武县| 南康市| 乐平市| 香格里拉县| 太原市| 仁怀市| 太仓市| 金堂县| 仁怀市| 罗平县| 柳江县| 普陀区| 罗源县| 钟祥市| 武隆县| 潜山县|