Why doesn't Java allow hiding static methods by instance methods?

后端 未结 4 2133
旧时难觅i
旧时难觅i 2021-02-20 03:25

As shown in http://docs.oracle.com/javase/tutorial/java/IandI/override.html, Java does allow

  1. Overriding an instance method by an instance method and
  2. Hidin
相关标签:
4条回答
  • 2021-02-20 04:11

    Another to add here is: 1. Static methods belong at the class level. So u cannot override method in the derived class. as simple its called hiding. :) 2. Instance methods belong to the objects, so objects are overrided. So we can override in the derived class.

    Above other comments give a good example have a look into it..

    Regards Punith

    0 讨论(0)
  • 2021-02-20 04:16

    Because, one are like Bananas and the other ones are Apples.

    Explaination:

    • Static Methods are created when reading the Class-Structure
    • Methods are created when a object of a class is created.

    Example:

    Foo.bar();
    

    is something different than

    new Foo().bar();
    

    Guess which one is called?

    Foo f = new Foo();
    f.bar();
    
    0 讨论(0)
  • 2021-02-20 04:19

    Simple answer: that would be the mess.

    Concrete answer: what to call in that case Derived.foo()? Base.foo() can't be called as it's hidden (as per you), Derived.foo() can't be called as it's not static.

    0 讨论(0)
  • 2021-02-20 04:27

    I suspect it is to avoid confusion with dealing with the base class. In fact I imagine the designers didn't see an obvious way this should behave.

    class Base {
        static void foo () {}
    }
    
    class Derived extends Base {
        void foo () {} // say this compiled
    }
    
    Base b = new Derived()
    b.foo(); // should the static or the virtual method be called?
    

    Should b.foo() call Base.foo() or should it potentially call Derived.foo()?

    0 讨论(0)
提交回复
热议问题