Consider the followoing code
interface MyInterface{
void method(String s);// if we write static modifier we have compile error
}
class MyClass implements MyInterface{
public static void main(String[] args){
myMethod(new Object());//Compile error
}
static void method(String s){...}// compile error
static void myMethod(Number n){...}
}
method()
with static modifier? Consider the following code
Object someObj;
...
Number n= (Number) someObj;
What compiler is doing when we cast to Number
in this case?
Why we cant define static method in interface?
Interfaces are designed to work with polymorphism, basically. Polymorphism How would you know which implementation to call when calling a static method on an interface?
// Should that invoke MyClass.method or MyOtherImplementation.method?
MyInterface.method("foo");
Next:
Why we cant implements method() with static modifier?
The idea is that the method is called on some object which implements the interface - which makes it an instance method.
When we are calling myMethod with reference to Object we have compile error. As i understood, compiler doesnt cast automatically, isnt it?
No, the compiler doesn't cast automatically. There's no implicit conversion from Object
to Number
, so you can't call a method with a parameter of type Number
with an argument of type Object
.
What compiler is doing when we cast to Number in this case?
It's validating that the value of someObj
is either null or a reference to an instance of Number
or a subclass.
See more on this question at Stackoverflow