Reducing the visibility of a static method

后端 未结 4 2167
面向向阳花
面向向阳花 2020-12-11 09:38

I know that a child cannot reduce the visibility of a non-static method and I understand why it is so.

I\'ve read however that \"static method can be hidden through

4条回答
  •  感动是毒
    2020-12-11 10:09

    Based on hagubear's valuable comments, it seems that the author of a statement meant hiding a method through overloading it with a method having the same declaration.

    Quoting this link:

    We can declare static methods with same signature in subclass, but it is not considered overriding as there won’t be any run-time polymorphism. (...) If a derived class defines a static method with same signature as a static method in base class, the method in the derived class hides the method in the base class.

    Thus, defining a method in a child class having exact same declaration effectively hides the original method in child. However, as in case of fields, casting to the parent will restore the original access.

    Sample code:

    public class Test {
        public static void main( String[] args ) {
            B b = new B();
            A a = b;
            b.f(); // "Access somewhat denied"
            a.f(); // "f()"
        }
    }
    class A { 
        public static void f() { 
             System.out.println("f()");
        }
    }
    class B extends A { 
        // *must* be public
        public static void f() { 
             System.out.println("Access somewhat denied");
        }
    }
    

提交回复
热议问题