A class cannot access the implemented interface's static method using 'this' and should use the type name to get to the method. This makes perfect sense to me - The static method is not bound to an instance and therefore 'this' has no meaning in this case (and is also not inherited to be able to reach via 'this' from the class).
But I'm baffled why did the following compile:
Why is the compiler seeing the interface's static variable differently? Appreciate your replies.
I think it can be connected to the fact, that there is no concept of override in java in regards to variables. Variables are always hidden, thus, we can be sure which variable we reference at compile time given by reference type. This does not apply to methods, and it is therefore different.
Actually, its probably not the case. The different handling of static interface methods and variables still handles same issue of ambiguity.
So basically, with static interface methods, issue of ambiguity is handled more proactively.
[update] And again, if we provide boolean field for TestClass itself, the compilation error of referencing 'tc.flag' disappears, even if both interfaces have that same field also. So I would say with variables, its similar case as with default interface methods (if both interfaces have it, concrete class has to provide own implementation, if only one interface has it, its OK).
What does the JLS (Java® Language Specification) say?
Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.
So ML's fields will all behave as final fields.
By the way: a static interface method isn't inherited by its implementing classes. I think you will find something about that in this JLS section. Yes, here it is:-
A class does not inherit private or static methods from its superinterfaces.
I have forgotten what the rules would be if both those getNumber() methods were declared as instance type, but you could get it to compile somehow. You would probably have to override that method in the concrete class.
joke time: What is brown and sticky? ... ... ... A stick! Use it to beat this tiny ad!