Is it possible to hide or lower access to Inherited Methods in Java?

前端 未结 8 654
死守一世寂寞
死守一世寂寞 2021-01-08 00:04

I have a class structure where I would like some methods in a base class to be accessible from classes derived directly from the base class, but not classes derived from der

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-08 00:48

    It is possible, but requires a bit of package manipulation and may lead to a structure that is a bit more complex than you would like to work with over the long haul.

    consider the following:


    package a;
    
    public class Base {
        void myMethod() {
            System.out.println("a");
        }
    }
    

    package a;
    
    public class DerivedOne extends Base {
        @Override
        void myMethod() {
            System.out.println("b");
        }
    }
    

    package b;
    
    public class DerivedTwo extends a.DerivedOne {
        public static void main(String... args) {
            myMethod(); // this does not compile...
        }
    }
    

    I would recommend being nice to yourself, your co-workers and any other person that ends up having to maintain your code; rethink your classes and interfaces to avoid this.

提交回复
热议问题