Sam
Sam

Reputation: 6910

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?

Upvotes: 3

Views: 344

Answers (4)

Raghu
Raghu

Reputation: 470

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.

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

The getWord() method in class BMW is not called when you call BMW.print() because static methods are associated with a class, not an instance of a class. Once you make the call to the static method BMW.print(), several things are required:

  • All method calls made from BMW.print() must also be static methods if they are defined inside the BMW class
  • There is no concept of inheritance, i.e. calling the getWord() method will not propagate to a child class. The reason for this is that getWord() is a static method associated with the Car class itself.

If you really wanted to get your current code to print "BMW", you could try the following (which isn't very good design):

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

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

Upvotes: 2

questzen
questzen

Reputation: 3297

In Java: fields & static methods do not adhere to dynamic/runtime polymorphism. When you call BMW.print(), it inherits the static definition from Car. Being a static function call it refers to Car.getWord()

Upvotes: 2

Raphael
Raphael

Reputation: 1812

Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. runtime) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time).

Upvotes: 7

Related Questions