You didn't override anything here. To see for yourself, Try putting @Override
annotation before public static void a()
in class B
and Java will throw an error.
You just defined a function in class B
called a()
, which is distinct (no relation whatsoever) from the function a()
in class A
.
But Because B.a()
has the same name as a function in the parent class, it hides A.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,
B b = new B();
b.a() //prints B.a()
A a = (A)b;
a.a() //print A.a(). Uses the declared reference's class to find the method.
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?
B.a()
is only accessible via classB
. If you have something likeA a = new B(); a.a();
, it will print "A.a()", even though it's of type B. If it were truly overridden, then it would have printed "B.a()". Note that it is Java's odd feature that allows you to call static methods from an object instance that helps sow confusion here. – dleva
insideB
? You can test that easily by adding@Override
annotation before that method. – Pshemoa()
is inherited byB
if you remove thea()
function fromB
. It does inherit, but it does not override. Instead it hidesa()
if you declare anothera()
function inB
. – Dorus