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?

2
  • The second method needs an object instance of class ABC1. Commented May 8, 2017 at 12:51
  • Because overriding only makes sense with polymorphic, instance methods? Commented May 8, 2017 at 12:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Someone with that high rep should not answer obvious duplicates...
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.
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.
Not sure if I get you. Long story short: is there anything I could do to make this answer accept-worthy in your eyes?
Thanks for your answer GhostCat. I was able to understand the things with practical explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.