Why is overriding of static methods left out of most OOP languages?

▼魔方 西西 提交于 2019-12-10 00:30:56

问题


It is certainly not for good OOP design - as the need for common behavior of all instances of a derived class is quite valid conceptually. Moreover, it would make for so much cleaner code if one could just say Data.parse(file), have the common parse() code in the base class and let overriding do its magic than having to implement mostly similar code in all data subtypes and be careful to call DataSybtype.parse(file) - ugly ugly ugly

So there must be a reason - like Performance ?

As a bonus - are there OOP languages that do allow this ?

Java-specific arguments are welcome as that's what I am used to - but I believe the answer is language agnostic.

EDIT : one could ideally :

<T> void method(Iface<? extends T> ifaceImpl){
    T.staticMeth(); // here the right override would be called
}

This will also fail due to erasure (in java at least) - if erasure is at work one needs (would need) to actually pass the class :

<T, K extends T> void method(Iface<K> ifaceImpl, Class<K> cls){
    cls.staticMeth(); // compile error
}

Does it make sense ? Are there languages doing this already ? Is there a workaround apart from reflection ?


回答1:


Speaking to C++

class Foo {
public:
    static  void staticFn(int i);
    virtual void virtFn(int i);
};

The virtual function is a member function - that is, it is called with a this pointer from which to look up the vtable and find the correct function to call.

The static function, explicitly, does not operate on a member, so there is no this object from which to look up the vtable.

When you invoke a static member function as above, you are explicitly providing a fixed, static, function pointer.

foo->virtFn(1);

expands out to something vaguely like

foo->_vtable[0](foo, 1);

while

foo->staticFn(1);

expands to a simple function call

Foo@@staticFn(1);

The whole point of "static" is that it is object-independent. Thus it would be impossible to virtualize.



来源:https://stackoverflow.com/questions/20291984/why-is-overriding-of-static-methods-left-out-of-most-oop-languages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!