Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override vs Shadowing in Java [duplicate]

Tags:

java

What is the difference between overriding and shadowing in particular to this statement “A static method cannot be overriden in a subclass, only shadowed"

like image 256
duckduck Avatar asked Jun 30 '26 15:06

duckduck


2 Answers

If you were truly overriding a method, you could call super() at some point in it to invoke the superclass implementation. But since static methods belong to a class, not an instance, you can only "shadow" them by providing a method with the same signature. Static members of any kind cannot be inherited, since they must be accessed via the class.

like image 61
Thorn G Avatar answered Jul 02 '26 03:07

Thorn G


Overrideing... This term refer to polymorphic behavior for e.g

class A {
   method(){...} // method in A
}

class B extends A {
    @Override
    method(){...} // method in B with diff impl.
}

When you try to invoke the method from class B you get overriden behvaior ..e.g

A myA = new B();
myB.method();   // this will print the content of from overriden method as its polymorphic behavior

but suppose you have declared the method with static modifier than by trying the same code

A myA = new B();
myA.method();  // this will print the content of the method from the class A

this is beacuse static methods cant be overriden ... the method in class B just shadow the method from class A...

like image 30
Jalpan Randeri Avatar answered Jul 02 '26 04:07

Jalpan Randeri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!