简体   繁体   中英

What's the semantical difference between the two statements?

I have two (pretty useless) interfaces with test1 extending test

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

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

I have a class MyClass (again a bit useless) implementing the test1 interface

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

Out of the code I've provided, I'm interested in knowing what is the semantical difference (if any) between the two statements ordered as 1. and 2. respectively; Because result wise, correct me if I'm wrong they're pretty much the same.

So, interface variables are by default public static final . There is no difference between ((test)this).a and test.a as for ((test)this) compiler expect a reference type of test . For compiler this really does not matter. For example

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

The above line also work and gives you proper output.

There is no difference. But it's not a good practice to refer to static members through an instance reference.

Casting this to a parent to access its static field is really misleading.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM