Overriding interface's variable?

我们两清 提交于 2019-11-29 03:59:14

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

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.

Default signature for any variable in an interface is

public static final ...

So you cannot override it anyhow.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!