Java 10'var'和继承

时间:2018-04-10 03:35:12

标签: java var java-10

在查看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能够识别变量所包含的派生类类型。并且在执行myA.someMethod()时执行B:someMethod()而不是A:someMethod()。

确实如此吗?

1 个答案:

答案 0 :(得分:9)

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

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:我尝试用一​​个包含匿名类的var玩一点,并想出了这个有趣的行为 - 再次感谢nullpointer提到它是why can't we assign two inferred variables as an anonymous class to each other的副本:

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() {
                ^

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

令人惊讶的是,错误消息不再精确 - 目前没有意义,因为错误中显示的类型名称是相同的!