I know that we cannot override static methods in Java, but can someone explain the following code?
class A {
public static void a() {
System.out.println("A.a()");
}
}
class B extends A {
public static void a() {
System.out.println("B.a()");
}
}
How was I able to override method a()
in class B
?
You didn't override anything here. To see for yourself, Try putting
@Override
annotation beforepublic static void a()
in classB
and Java will throw an error.You just defined a function in class
B
calleda()
, which is distinct (no relation whatsoever) from the functiona()
in classA
.But Because
B.a()
has the same name as a function in the parent class, it hidesA.a()
[As pointed by Eng. Fouad]. At runtime, the compiler uses the actual class of the declared reference to determine which method to run. For example,You cannot override static methods in Java. Remember
static
methods and fields are associated with the class, not with the objects. (Although, in some languages like Smalltalk, this is possible).I found some good answers here: Why doesn't Java allow overriding of static methods?
You didn't override the method
a()
, becausestatic
methods are not inherited. If you had put@Override
, you would have seen an error.But that doesn't stop you from defining static methods with the same signature in both classes.