3

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

duckduck
  • 167
  • 2
  • 2
  • 9
  • It is actually called [hiding](http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.8), not shadowing. – assylias Jun 17 '13 at 17:48
  • Shadowing is (at least in my experience) something you use so that interrupts on a microcontroller don't screw up the thread being executing at the time. The shadow registers are updated every time the real ones are changed in the main thread, but stop updating when he microcontroller is is interrupted so the registers can be restored from them when the interrupt routine exits. – AJMansfield Jun 17 '13 at 17:52
  • 1
    well, there are shadowing, obscuring, and hiding ... but he's right in that the one related inheritance is hiding. Hiding happens when a static member in a sub class hides one on the super class. Specification states: If a class declares a static method m, then the declaration m is said to hide any method m', where the signature of m is a subsignature (§8.4.2) of the signature of m', in the superclasses and superinterfaces of the class that would otherwise be accessible to code in the class. – Rafael Apr 08 '14 at 19:29

2 Answers2

4

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.

Thorn G
  • 12,620
  • 2
  • 44
  • 56
  • 1
    **static** members can be access via object instance as well using **this.staticVariable**, but is considered bad practice. – NoName Jun 22 '17 at 14:50
1

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...

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Jalpan Randeri
  • 223
  • 2
  • 10