java - Why can't implementing classes define an overriding method as static? -
i'm confused why following not allowed:
public interface myinterface { myinterface getinstance(string name); } public class myimplementation implements myinterface { public myimplementation(string name) { } @override public static myinterface getinstance(string name) { // static not allowed here return new myimplementation(name) } } i understand why method in interface cannot static, why can't overriding method be?
i want classes implement getinstance(string name) method, i'm limited being able call method if object has been instantiated kind of defeats purpose...
*update:* answers, understand better now. shouldn't trying make utility class (or factory class matter) implement interface (or @ least, not in way)...
invoking static methods in java requires specify exact type. not possible invoke static methods polymorphically, eliminating need @override.
please note approach not universal across languages: example, can override class methods in objective-c, , apple's cocoa frameworks make use of mechanism customize "factory" classes. however, in java, c++, , c# class methods not support polymorphic behavior.
theoretically, java designers have let provide interface method implementations through static methods in case implementation not need access state instance. same behavior simple achieve trivial wrapper:
public class myimplementation implements myinterface { public myimplementation(string name) { } @override public myinterface getinstance() { // static not allowed here return getinstanceimpl(); } public static getinstanceimpl() { return new myimplementation(name) } } java compiler have done same thing on behalf, seeing static method implement instance method both unusual , confusing, guess java designers decided against providing "piece of magic".
Comments
Post a Comment