Is there a way to have a public method, which won't be inherited?
I have a class, with public API.
I have other classes who inherit f开发者_运维问答rom that class. I do not make use of all the APIs inherited from the first class.If I change the order of inheritance, then I have even more API methods I do not wish classes to inherit.
Languages: PHP and C#
If some method should not be in inherited class, you probably should not place its in base class. Second class could implement some interface which has that method, or inherit by another class which has that method and is inherited by current base-class.
Is there any specific reason why you would want such method? I think you should consider putting the functionality you want your classes to inherit in an interface. Other functionality should be implemented as private methods.
Also consider breaking down the functionality into several classes and then using Composition instead of inheritance. If you use inheritance to compose complex class hierarchies, they will always be difficult to manage. You should favor composition over inheritance.
I would suggest you to use Decorator pattern.
If we call the base class B and the derived classes D1, D2...
Two approaches are:
Split B into two classes: the private implementation (abstract B) and the public methods (that you wish to hide in your other 2 classes), D3. So to "use" the base class you instantiate D3. Then D1,D2 only inherit the private implementation of B because the public interface for "B" is only available through D3. (If you still need some of the public functionality in D1,D2 but don't want it to be public, then simply add it as a private method od B, and then add a public proxy method in D3 that exposes it and simply calls down to the base class implementation.
Don't derive your classes from B. Embed an instance of B in D1,D2 and simply expose a new interface in those classes that only makes the "limited functionality" available.
I do not make use of all the APIs inherited from the first class
put those methods to a public sealed class
I have other classes who inherit from that class.
use Interface of base class with virtual methods for that.
精彩评论