Why do we say that a static method in Java is not a virtual method?

前端 未结 5 1794
北恋
北恋 2021-01-05 06:58

In object-oriented paradigm, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a f

5条回答
  •  自闭症患者
    2021-01-05 07:33

    You can't override static methods. They are bound at compile-time. They are not polymorphic. Even if you try to invoke it as if it were an instance method (which IMO you shouldn't do) it's bound to the compile-time type of that expression, and the execution-time value is completely ignored (even if it's null):

    Thread otherThread = null;
    otherThread.sleep(1000); // No errors, equivalent to Thread.sleep(1000);
    

    This behaviour can be very confusing for a reader, which is why at least some IDEs allow you to generate warnings or errors for accessing static members "through" a reference. It was a flaw in Java's design, pure and simple - but it doesn't make static methods virtual at all.

提交回复
热议问题