2
class Abc{
public  static void hello(){
    System.out.println("parent");//Line1
 }
}

class Abc1 extends Abc{
public  void hello(){//Line2
    System.out.println("child");//Line3
 }
}

Compiler gives error at line 3 saying that

This instance method cannot override the static method from Abc

Why can static methods not be overridden by a instance method?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Prasad
  • 1,089
  • 13
  • 21

1 Answers1

2

Simple: because the language specification says so.

That is one of the downsides of static methods: there is no polymorphism for them! Conceptually, they are not meant to be overridden. That is all there is to this.

To be precise: the JLS says differentiates between static and non-static method and states:

An instance method is always invoked with respect to an object, which becomes the current object to which the keywords this and super refer during execution of the method body.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Someone with that high rep should not answer obvious duplicates... – Murat Karagöz May 08 '17 at 12:53
  • True. But I tend to keep my answer here - as it gives a certain insight that is not find on that DUP; at least not in that clear wording. But I hear you. Will resist harder the next time. – GhostCat May 08 '17 at 12:54
  • I was able to find the answer. If i create object of Abc1 and assign it Abc(Abc a = new Abc1()).then if I try to to call a.hello() method,at runtime JVM doesn't understand whether it has to call the static method with reference or instance with the object,Which in turn creates the ambiguity. – Prasad May 09 '17 at 04:40
  • Not sure if I get you. Long story short: is there anything I could do to make this answer accept-worthy in your eyes? – GhostCat May 09 '17 at 05:02
  • Thanks for your answer GhostCat. I was able to understand the things with practical explanation. – Prasad May 09 '17 at 05:12