651.288.7000 info@intertech.com

Recently, I had a quick chat with a colleague on static methods in parent and sub-classes with the same signature. The source of the conversation was the terms “hiding” vs. “overriding”, and why “hiding static methods” is correct and works but “overriding static methods” is incorrect and does not work.

TL;DR “You can’t override static methods”, because the JVM executes static methods on the declared reference class, not the defined runtime/instance class.

A simple example shows a few different static method execution contexts, illustrating the results:

The main method comments state the execution results.  The results show that the called static method is the one for the defined reference.

Running the child class as a Java app (the main method) outputs:

PARENT
PARENT
CHILD
CHILD

It’s no different than replacing the instance method calls with the more correct static reference call:

Hopefully this post helps explain hiding static methods – why we cannot override static methods but we can hide static methods.

 

Like What You've Read?

Subscribe to the Blog.

Every Friday we send that week's content from our Developers via email. Try it out!

Some ad blockers can block the form below.

You have Successfully Subscribed!

Pin It on Pinterest

Share This