I have read about method hiding concept in Java but I am not sure I understand the advantages. In which cases would method hiding be useful?

有帮助吗?

解决方案

You can read more here http://docs.oracle.com/javase/tutorial/java/IandI/override.html

In short, the benefit is that you can implement a static method in a subclass which has the same signature as a static method in a superclass. If you could not do this, you couldn't add such methods to sub classes, and if you added such a method to a superclass all its subclasses would fail to compile.

BTW: You can make a static method not allow hiding by making it final.

class Superclass {
    public static final void method() { }
}

class Subclass extends Superclass {
    public static void method() { } // doesn't compile
}

to allow a method to be hidden you can make it non-final

class Superclass {
    public static void method() { }
}

其他提示

There is no "benefit" to this, it is simply how the language specification decided to deal with situations when static methods of related classes happen to have the same signature. The language designers found no sensible way to provide an "override" functionality1, so they took the easy way out.


1 There is a way to make overrides of static methods work on an abstract OO level, as evidenced by the way it is done in Objective-C. However, the alternative is harder to understand.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top