Reputation: 6910
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
Reputation: 470
According to characteristics of static methods,
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
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:
BMW.print()
must also be static
methods if they are defined inside the BMW
classgetWord()
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
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
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