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

前端 未结 8 608
死守一世寂寞
死守一世寂寞 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:40

    When overriding a method you can only make it more public, not more private. I don't know why you use the word "general"

    Remember that, ordering from least to most restrictive:

    public<protected<default<private
    

    Yes, "protected" is a less restrictive access modifier than default (when no modifier is used), so you can override a default method marking the overriding method as protected, but not do the opposite.

    Can: You can override a protected method with a public one.

    Can't: You can't override a public method with a protected one.

    0 讨论(0)
  • 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()
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-08 00:50

    If you did this then DerivedOne would not be a Base, from the DerivedTwo's point of view. Instead what you want is a wrapper class

    //Uses myMethod but keeps it hidden
    public class HiddenBase {
        private final Base base = new Base();
        private void myMethod();
        public void otherMethod() {base.otherMethod();}
    }
    

    You can't access protected methods of the base though this way...

    0 讨论(0)
  • 2021-01-08 00:50

    Inheritance works because everywhere you can use the base class, you can also use one of it's subclasses. The behavior may be different, but the API is not. The concept is known as the Liskov substitution principle.

    If you were able to restrict access to methods, the resulting class would not have the same API and you would not be able to use substitute an instance of the base class for one of the derived classes, negating the advantage of inheritance.

    What you actually want to accomplish can be done with interfaces:

    interface IBase1 {
    }
    
    class Derived1 implements IBase1 {
      public void myMethod() {
      }
    }
    
    class Derived2 implements IBase1 {
    }
    
    class UseMe {
      public void foo(IBase1 something) {
         // Can take both Derived1 and Derived2
         // Can not call something.myMethod()
      }
      public void foo(Derived1 something) {
         something.myMethod();
      }
      public void foo(Derived2 something) {
        // not something.myMethod()
      }
    }
    
    0 讨论(0)
  • 2021-01-08 00:55

    I think the very nature of the problem as you've posed it exposes conceptual problems with your object model. You are trying to describe various separate responsibilities as "is a" relationships when actually what you should be doing is describing "has a" or "uses a" relationships. The very fact that you want to hide base class functionality from a child class tells me this problem doesn't actually map onto a three-tiered inheritance tree.

    It sounds like you're describing a classic ORM problem. Let's look at this again and see if we can re-map it onto other concepts than strict "is a" inheritance, because I really think your problem isn't technical, it's conceptual:

    You said:

    The base class is the base table class managing the database handling part of it. There is a fair amount of functionality contained in it that is common to all table types - as once they are in the database they become uniform.

    This could be more clear, but it sounds like we have one class that needs to manage the DB connection and common db operations. Following Single Responsibility, I think we're done here. You don't need to extend this class, you need to hand it to a class that needs to use its functionality.

    The middle class is specific to the kind of table in the file being parsed, and has the table parsing and import logic. It needs access to some of the base class's database access functions.

    The "middle class" here sounds a bit like a Data Mapper. This class doesn't need to extend the previous class, it needs to own a reference to it, perhaps injected on the constructor or a setter as an interface.

    The top level class is specific to the table and does nothing more than initialize the table's layout in a way the parent classes can understand. Also users of the base class do not need to see or access the database specific functions which the middle class do. In essence, I want to reveal these functions only to one level above the base class and no one else.

    I'm not clear why a high-level class seems to have knowledge of the db schema (at least that's what the phrase "initialize the table's layout" suggests to me), but again, if the relationship between the first two classes were encapsulation ("has a"/"uses a") instead of inheritance ("is a"), I don't think this would be a problem.

    0 讨论(0)
提交回复
热议问题