Java – override interface variables?
•
Java
When I read from various java books and tutorials, the variables declared in the interface are constants and cannot be overwritten
I made a simple code to test it
interface A_INTERFACE
{
int var=100;
}
class A_CLASS implements A_INTERFACE
{
int var=99;
//test
void printx()
{
System.out.println("var = " + var);
}
}
class hello
{
public static void main(String[] args)
{
new A_CLASS().printx();
}
}
And print out var = 99
Is var covered? I'm completely confused. Thank you for any suggestions!
Thank you very much! I'm new to this interface "Shadow" is a key word to understand this I checked the relevant information and now I understand
Solution
It will not be covered, but obscured, and there is confusion, because the constants in the interface are also static
Try this:
A_INTERFACE o = new A_CLASS(); System.out.println(o.var);
You should get a compile - time warning for non - static access to static fields
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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
