2

I read in lots of places that a static method cannot be overridden. However, I wrote a sample query to test, it seemed my static method was overridden.

Below is my query:

public class staticTestDriver{

    public static void main(String[] args){
        subClass.print(); //seems the print() method has been overridden
    }
}

class superClass {
    static void print(){
        System.out.println("this is static");
    }
}

class subClass extends superClass{
    static void print(){
        System.out.println("This is overridden");
    }
}

The output is "this is overridden". Any ideas?

Joann.B
  • 121
  • 1

2 Answers2

0

Since static methods are invoked by specifying the class name explicitly, any attempt of polymorphism is void.

In other words. It's true that you can shadow/hide/replace static methods in a sub class, but since you never invoke static methods on any instance, the sole purpose of overriding anything is lost. You know already at compile time which class you are invoking.

So even though your code is valid java, it does not fulfill the definition of an overridden method.

JHH
  • 8,567
  • 8
  • 47
  • 91
  • Java does allow you to call static methods using a reference to an instance. Otherwise the whole "hiding" definition would not exist. – RealSkeptic Apr 26 '15 at 20:52
  • Yes you're right. But which method to invoke is based on the declared type of the variable, not on the actual type of the instance. But you're right in that this makes my answer confusing. – JHH Apr 26 '15 at 20:57
0

Thanks everyone. I found an article that gives a very well explanation of this situation. Please check the answer here

Also, I agree with you that this is not applicable to overriding. Because "overriding depends on having an instance of a class." (reference here)

So if I do the code mentioned by Robert Bain

 superClass myClass = new subClass(); myClass.print();

The output will be "this is static", meaning no overriding happened.

Community
  • 1
  • 1
Joann.B
  • 121
  • 1