【问题标题】:What's the semantical difference between the two statements?这两个语句之间的语义区别是什么?
【发布时间】:2018-02-17 15:25:18
【问题描述】:

我有两个(非常没用的)interfacestest1 扩展 test

interface test
{
    int a = 8;
    void show();
}

interface test1 extends test
{
    int a = 4;
    void show();
}

我有一个类MyClass(又有点没用)实现test1 接口

public class MyClass implements test1
{
    public void show()
    {
       System.out.println(((test)this).a);    // 1
       System.out.println(test.a);            // 2
    }
    public static void main(String ar[])
    {
        new MyClass().show();
    }
}

在我提供的代码中,我有兴趣了解按 1. 排序的两个语句之间的语义差异(如果有的话)和2. 分别;因为结果是明智的,如果我错了,请纠正我,它们几乎是一样的。

【问题讨论】:

    标签: java interface casting static this


    【解决方案1】:

    因此,接口变量默认为public static final((test)this).atest.a 之间没有区别,因为 ((test)this) 编译器期望引用类型为 test。对于编译器 this 真的没关系。例如

    System.out.println(((test)null).a);
    

    上面的行也可以工作,并为您提供正确的输出。

    【讨论】:

      【解决方案2】:

      没有区别。但是通过实例引用来引用静态成员并不是一个好习惯。

      this 投射到父级以访问其静态字段确实具有误导性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-16
        • 2022-01-02
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 1970-01-01
        • 2015-05-31
        • 2020-11-01
        相关资源
        最近更新 更多