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

前端 未结 8 659
死守一世寂寞
死守一世寂寞 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条回答
  •  独厮守ぢ
    2021-01-08 00:47

    What you describe comes close to what the protected access class is for, derived classes can access, all others cannot.

    If you inherit from base classes you have no control over this might pose a problem, you can make the method inaccesible to others by throwing an exception while making the inherited code available to your classes by calling super directly, something like:

    // Uses myMethod and then hides it.
    public class DerivedOne extends Base {
        @Override
        public void myMethod() {
            throw new IllegalStateException("Illegal access to myMethod");
        }
    
        private void myPrivateMethod() {
            super.myMethod();
        }
    
    }
    

    Edit: to answer your elaboration, if I understand you correctly you need to specify behaviour in the context of the base class which is defined in the middle class. Abstract protected methods won't be invisible to the classes deriving from the middle class.

    One possible approach is to define an interface with the methods you would need to be abstract in the base class, keeping a private final reference in the base class and providing a reference to the implementation when constructing the middle class objects.

    The interface would be implemented in a (static?) nested inside the middle class. What I mean looks like:

    public interface Specific {
        public void doSomething();
    }
    
    public class Base {
        private final Specific specificImpl;
    
        protected Base(Specific s) {
            specificImpl = s;
        }
    
        public void doAlot() {
    
             // ...
    
             specificImpl.doSomething();
    
             // ...
        }
    }
    
    public class Middle extends Base {
    
        public Middle() {
            super(new Impl());
        }
    
        private Impl implements Specific {
    
            public void doSomething() {
    
                System.out.println("something done");
            }
        }
    }
    
    public class Derived extends Middle {
    
        // Access to doAlot()
        // No access to doSomething()
    }
    

提交回复
热议问题