Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Static methods are treated as global by the JVM, there are not bound to an object instance at all.</p> <p>It could conceptually be possible if you could call static methods from class objects (like in languages like Smalltalk) but it's not the case in Java. </p> <p><strong>EDIT</strong></p> <p>You can <em>overload</em> static method, that's ok. But you can not <em>override</em> a static method, because class are no first-class object. You can use reflection to get the class of an object at run-time, but the object that you get does not parallel the class hierarchy. </p> <pre><code>class MyClass { ... } class MySubClass extends MyClass { ... } MyClass obj1 = new MyClass(); MySubClass obj2 = new MySubClass(); ob2 instanceof MyClass --&gt; true Class clazz1 = obj1.getClass(); Class clazz2 = obj2.getClass(); clazz2 instanceof clazz1 --&gt; false </code></pre> <p>You can reflect over the classes, but it stops there. You don't invoke a static method by using <code>clazz1.staticMethod()</code>, but using <code>MyClass.staticMethod()</code>. A static method is not bound to an object and there is hence no notion of <code>this</code> nor <code>super</code> in a static method. A static method is a global function; as a consequence there is also no notion of polymorphism and, therefore, method overriding makes no sense. </p> <p>But this could be possible if <code>MyClass</code> was an object at run-time on which you invoke a method, as in Smalltalk (or maybe JRuby as one comment suggest, but I know nothing of JRuby).</p> <p>Oh yeah... one more thing. You can invoke a static method through an object <code>obj1.staticMethod()</code> but that really syntactic sugar for <code>MyClass.staticMethod()</code> and should be avoided. It usually raises a warning in modern IDE. I don't know why they ever allowed this shortcut.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload