-1

For example, class Base has two public methods: foo() and bar(). Class Derived is inherited from class Base (I cannot modify this class, as its a in a library I use).

In class Derived (Its in my application), I want to make foo() public but bar() private. Is the following code the correct and natural way to do this? Instead of extending it, I am creating a object and accessing only the required methods.

    class Base {
       public void foo();
       public void bar();
    };

    public class Derived {
         private Base base;

         public void bar() {
            base.bar();
         }
    };
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Aksanth
  • 269
  • 2
  • 13
  • 1
    there is no inheritance in the code you show. what do you mean, you want to make an inherited method 'private'? that is not possible – Stultuske Jan 16 '19 at 18:06
  • 1
    It makes no sense to make an inherited public method private in the derived class. The derived class must be able to substitute the base class. This would not work if a method from the base class is no longer available due to visibility constraints. – Donat Jan 16 '19 at 18:11
  • This is composition (eg a very simple facade or adapter), not inheritance. – Mark Rotteveel Jan 16 '19 at 18:22

2 Answers2

1

You cannot reduce the visibility of a method you inherit from

So if the super method is public you cannot reduce to protected or private

This question already covers it : Cannot reduce visibility of method inherited method from parent

sp00m
  • 47,968
  • 31
  • 142
  • 252
jml
  • 624
  • 5
  • 11
0

You cannot inherit from a class and reduce the visibility of the inherited methods. On the other hand, the code you are showing is not making use of inheritance. If you need to extend a class (so that you inherit all state and behavior from the base class), but also don't want to expose all inherited methods as public, here's a way to do it:

public final class Derived {

    private final Base base = new Base() { // extending base class here

        @Override
        public void foo() {
            Derived.this.foo();
        }

        @Override
        public void bar() {
            Derived.this.bar();
        }
    };

    public void foo() {
        // Implement foo here
    }

    private void bar() {
        // Implement bar here
    }
}

So the idea is to encapsulate the implementation of a class that extends Base in a private final field of a new Derived class that only exposes the foo method, while keeping the bar method private. This anonymous inner class just delegates to methods of the Derived class. As an extra safety measure, we are also making the Derived class final.

fps
  • 33,623
  • 8
  • 55
  • 110