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
?
Static methods will called by its Class name so we don't need to create class object we just cal it with class name so we can't override static
for example
we just call it
AClass.test();
means static class can't be overridden if it's overridden then how to cal it .
static
methods are not inherited so itsB
's separate copy of methodstatic
are related toclass
not the state ofObject
Also, the choice of method to call depends on the declared type of the variable.
At (1), if the system cared about the identity of
b
, it would throw aNPE
. and at (2), the value ofa
is ignored. Sincea
is declared as anA
,A.a()
is called.While goblinjuice answer was accepted, I thought the example code could improved:
Produces:
If B had overridden
print()
it would have write B on the final line.Your method is not overridden method. you just try to put @Override annotation before your method in derived class. it will give you a compile time error. so java will not allow you to override static method.
That's called
hiding a method
, as stated in the Java tutorial Overriding and Hiding Methods: