0

Why can't we override a non-static method to make it static. I got this error when trying to do it :

This static method cannot hide the instance method from aSuperClass.

Many thanks!

sgarizvi
  • 16,623
  • 9
  • 64
  • 98
Huy Than
  • 1,538
  • 2
  • 16
  • 31

2 Answers2

2

Overriding means providing a new implementation in the child class for instance method, Instance method may or may not work with the class instance members. Its not logical to override them and redefine them as static. static means the method is related to the class, not to the instance of the class.

You can't do that in C# as well as Java.

For C# Look at override - MSDN

You cannot use the new, static, or virtual modifiers to modify an override method.

Habib
  • 219,104
  • 29
  • 407
  • 436
1

Static methods are not overridden in the way Polymorphism works. However when you try to override a static method Java allows the concept of Name Hiding.

Now coming to your question. A Static method can be invoked both by Class Name and Object name. If you override a non static method with a static one how will the compiler know which one to invoke.

static void f(){}

A obj = new A();

A.f() and obj.f() will both invoke the static method. If you put a Non-Static f() here the confusion starts for obj.f().

Manuel
  • 3,828
  • 6
  • 33
  • 48
Geek
  • 23,089
  • 20
  • 71
  • 85