Overriding interface's variable?

后端 未结 4 2022
抹茶落季
抹茶落季 2020-12-10 04:29

As I read from various Java book and tutorials, variables declared in a interface are constants and can\'t be overridden.

I made a simple code to test it

<         


        
相关标签:
4条回答
  • 2020-12-10 05:05

    Default signature for any variable in an interface is

    public static final ...
    

    So you cannot override it anyhow.

    0 讨论(0)
  • 2020-12-10 05:07

    The variable you declared in that interface is not visible to the class that implemented it.

    If you declare a variable in an static and final, i.e. a constant, THEN it is visible to implementors.

    0 讨论(0)
  • 2020-12-10 05:11

    You did not override the variable, you shadowed it with a brand-new instance variable declared in a more specific scope. This is the variable printed in your printx method.

    0 讨论(0)
  • 2020-12-10 05:19

    It is not overridden, but shadowed, with additional confusion because the constant in the interface is also static.

    Try this:

    A_INTERFACE o = new A_CLASS();
    System.out.println(o.var);
    

    You should get a compile-time warning about accessing a static field in a non-static way.

    And now this

    A_CLASS o = new A_CLASS();
    System.out.println(o.var);
    System.out.println(A_INTERFACE.var);  // bad name, btw since it is const
    
    0 讨论(0)
提交回复
热议问题