I am extending an existing library (lets call it Lib) that I cannot modify directly.
Is there any way to make some methods from Lib private so that they cannot be accessed outside of subclasses?
For example if I have:
class A extends Lib {
def fun(i: int) = someLibFunction(i) //someLibFunction is inherited from Lib
}
how can I make someLibFunction private in A, despite it being public/protected in Lib?
This would break the basic foundation of object-oriented programming – that you can use subclass everywhere where super class was expected (polymorphism).
If it was allowed to narrow down the visibility of a method (e.g. from
publictoprivate) client code receiving an instance ofLibwould not be allowed to receiveA extends Lib. Client code expectssomeLibFunction()to be accessible and subclass cannot change that contract.That being said neither Scala nor any object-oriented language is allowed to narrow down the visibility of any method when subclassing. Note that widening the visibility (e.g. from
protectedtopublicis perfectly possible).In other words you are not extending an existing API (library). You are creating a completely different API (library) that has a different contract.
Final example: you have a
Vehicleclass that has acapacity()and candrive().Carcan extendVehicleby adding some new capabilities likerefuel(). ButContainercannot extendVehicleand hide driving capability.Containercan containVehicle(or vice-versa), alsoContainerandVehiclemight have common parent likeCanHoldCargo.