Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. Hiding a static method by a static method

My question is why Java doesn't allow hiding a static superclass method by an instance method. This could be done like this:

class Base {
    static void foo () {}
}

class Derived extends Base {
    void foo () {}
    void access () {
        foo ();
        Base.foo ();
    }
}

I don't see any particular issue with the above approach - it is only as "messy/complex" as the (allowed) hiding of statics already is.

like image 1000
mafu Avatar asked Jan 30 '13 10:01

mafu


4 Answers

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()?

like image 111
Peter Lawrey Avatar answered Oct 17 '22 05:10

Peter Lawrey


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.

like image 35
Archer Avatar answered Oct 17 '22 07:10

Archer


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();
like image 35
Christian Kuetbach Avatar answered Oct 17 '22 05:10

Christian Kuetbach


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

like image 36
Punith Raj Avatar answered Oct 17 '22 06:10

Punith Raj