Why we cant define static method in interface?
All the methods of an interface are by default public abstract
. Using static
modifier doesn't make sense. Because the invocation of static methods aren't polymorphic. In the sense, you can't override them. You invoke the static methods on the class name only. Well, you can invoke them on some reference too, but that will be ultimately resolved on the basis of the declared type of the reference. Now, since the method is by default abstract, it doesn't make sense to invoke it. It doesn't have any body to do any task.
Why we cant implements method() with static modifier?
When you try to add static
modifier to the overridden method, it is not considered as being overriding. So, your class essentially have two different methods, with same name, same parameters, and same return type. That is of course not allowed inside a class.
Note that, you have to explicitly add public
modifier to the overriding method in the class, else your code won't compile. The reason being, you can't decrease the visibility of the overridden method in the subclass.
When we are calling myMethod with reference to Object we have compile error. As i understood, compiler doesnt cast automatically, isnt it?
Jave doesn't do automatic narrowing conversion. You need to add cast explicitly. But even if it allowed, how you expect your code to behave, because you are trying to refer a super class object with a subclass reference? You can of course make your code to compile by adding a cast while invoking the method:
myMethod((Number)new Object()); // This will compile, but fail at runtime
The above invocation will result in a ClassCastException
at runtime.
However, if you have an Object
reference refering to an object of any subclass of Number
, you can add an explicit cast, that will be type safe:
Object obj = new Integer(5);
Number num = (Number)obj; // This is fine. Because `obj` is referring to an `Integer`.
And finally, the signature of your main
method is not correct. You are missing the public
modifier.