Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a class A with 3 methods M1,M2,M3.
Class B is inherited from Class A & Class C is inherited from Class B.

Now all the methods in Class A are accessible for Class B & Class C.

Now i want to restrict
1)M1 & M2 of Class A for Class B
2)M3 for Class C .

How can i do this.
Posted

1 solution

You can't. And you shouldn't, even if it was possible. It makes no sense - why would you want to do that? If M1 and M2 are specific to B and M3 specific to C, then implement M1 and M2 in B and M3 in C.

It would violate the principle of polymorphism[^]: A subclass should behave like the baseclass if it is being used like the baseclass. If a B-class doesn't have access to M3 then you wouldn't be able to use it like an A-class.
 
Share this answer
 
v2
Comments
9000605667 3-Apr-15 4:56am    
I heard that with Dependency injection we can achieve this. But i don't know how to do.
Sascha Lefèvre 3-Apr-15 5:01am    
No - it's not possible at all (I edited my answer to give a bit more background on why it makes no sense, please read again if you haven't seen v2 yet).
Dependency injection doesn't have to do anything with that. And if you allow me to judge your experience by your question, you shouldn't bother with dependency injection yet, leave it for later :-)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900