Java 10 'var' 和继承

Java 10 'var' and inheritance

查看 var 功能后 here:

我在使用 JDK 10 设置我的 Eclipse/IntelliJ IDEA IDE 时遇到困难,因此我向拥有工作 Java 10 环境的 Stack Overflow 用户寻求帮助。

考虑以下因素:

public class A {
   public void someMethod() { ... }
}
public class B extends A{
   @Override
   public void someMethod() { ... }
}
...
...
...
var myA = new A(); // Works as expected
myA = new B(); // Expected to fail in compilation due to var being
               // syntactic sugar for declaring an A type
myA = (A) (new B()); // Should work
myA.someMethod(); // The question - which someMethod implementation is called?

当使用 var 时,我希望 JVM 能够识别变量持有的派生 class 类型。并在执行 myA.someMethod().

时执行 B:someMethod() 而不是 A:someMethod()

真的是这样吗?

感谢 nullpointer providing a link 在线 Java 10 编译器,我得到了以下有趣的结果:

public class Main {
    static class A {
           public void someMethod() { System.out.println(this.getClass().getName()); }
    }
    static class B extends A{
           @Override
           public void someMethod() { System.out.println("Derived: " + this.getClass().getName()); }
    }
    public static void main(String[] args) {
        var myA = new A();
        myA.someMethod();
        myA = new B(); // does not fail to compile!
        myA.someMethod();
    }
}

输出:

Main$A // As expected
Derived: Main$B  // As expected in inheritance

结论 - var 是语法糖: var myA = new A() 等同于 A myA = new A(),所有 OOP 都与之相关。

PS:我试着用一个持有匿名 class 的 var 玩了一会儿,并想出了这个有趣的行为 -(再次)感谢 nullpointer for mentioning it as a duplicate of :

static interface Inter {
    public void method();
}

public static void main(String[] args) {
    var inter = new Inter() {
        @Override
        public void method() {System.out.println("popo");}
    };
    inter.method();
    inter = new Inter() {
        @Override
        public void method() {System.out.println("koko");}
    };
    inter.method();
}

并且输出:

Main.java:11: error: incompatible types: <anonymous Inter> cannot be converted to <anonymous Inter>
        inter = new Inter() {
                ^

由于第二个匿名 class 类型与第一个匿名 class 类型不同,对 var 的第二次赋值失败 - 强制执行 var 关键字的语法糖角色。

令人惊讶的是,错误消息没有更细化 - 目前它没有什么意义,因为错误中显示的类型名称是相同的!