Search code examples
javaoopstatic-methodsoverridingmethod-hiding

hiding method in java inheritance


I have two class as following:

public class Car {
    public static void print() {
        System.out.println(getWord());
    }

    public static String getWord() {
        return "CAR";
    } 
}

public class BMW extends Car {
    public static String getWord() {
        return "BMW";
    } 
}

// main method
public static void main(String args[]) {
    BMW.print();
}

After I run above sample, this output is printed:

CAR

My question is: Why is the method getWord() not overriden?


Solution

  • According to characteristics of static methods,

    1. we cannot override static methods.
    2. If a method is static and you declare same method in the inherited class with the same as of base class it will not be hidden.

    Please check below rules from Java Doc :

    Overriding: Overriding in Java simply means that the particular method would be called based on the run time type of the object and not on the compile time type of it (which is the case with overriden static methods)

    Hiding: Parent class methods that are static are not part of a child class (although they are accessible), so there is no question of overriding it. Even if you add another static method in a subclass, identical to the one in its parent class, this subclass static method is unique and distinct from the static method in its parent class.