Search code examples
javaoverridingmethod-hiding

Benefit of method hiding in java


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?


Solution

  • 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() { }
    }