What is method hiding in Java? Even the JavaDoc explanation is confusing

前端 未结 7 1288
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 02:36

Javadoc says:

the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invo

7条回答
  •  眼角桃花
    2020-11-28 02:43

    When super/parent class and sub/child class contains same static method including same parameters and signature. The method in the super class will be hidden by the method in sub class. This is known as method hiding.

    Example:1

    class Demo{
       public static void staticMethod() {
          System.out.println("super class - staticMethod");
       }
    }
    public class Sample extends Demo {
    
       public static void main(String args[] ) {
          Sample.staticMethod(); // super class - staticMethod
       }
    }
    

    Example:2 - Method Hiding

    class Demo{
       public static void staticMethod() {
          System.out.println("super class - staticMethod");
       }
    }
    public class Sample extends Demo {
       public static void staticMethod() {
          System.out.println("sub class - staticMethod");
       }
       public static void main(String args[] ) {
          Sample.staticMethod(); // sub class - staticMethod
       }
    }
    

提交回复
热议问题