Continuing from this question: Why can't you reduce the visibility of a method in a Java subclass?
I need to create class B that is almost identical to class A, except that B cannot do certain things that A can.
Being a lazy programmer as I am, I tried to inherit A, only to greet with error that B cannot reduce the visibility of A methods. Duh!..
Now A is an API from a vendor, my intention is to encapsulate this API so that it is easier to use.
I wonder what is the best practice to work around this?
Two options:
If you need
Bto keep the same interface asA(so that client code can use any of the two without changes), you can override “forbidden” methods inBand have them throw anUnsupportedOperationException. For example:Or, if you really want the API of
Bto be a subset of the API ofA, then just haveBcontain an instance ofA, and delegate method calls appropriately.