开发者

Is there an access modifier that I can use hiding a abstract method from being called in a derived type?

开发者 https://www.devze.com 2023-02-03 06:23 出处:网络
Say I have a class1 that derives from abstract class2.Class2 has an abstract method that each derived class must override.In my design the method will only be called if cla开发者_StackOverflowss1 is c

Say I have a class1 that derives from abstract class2. Class2 has an abstract method that each derived class must override. In my design the method will only be called if cla开发者_StackOverflowss1 is casted to class2. Is there a way to hide this method when it is casted as class1? Not really a problem for me if not just wondering. If it is possible is this a good/bad idea and why? Thanks!!!


You could use explicit interface implementation to achieve a similar effect. To call an explicitly implemented interface method you need to cast to the interface.


I seriously doubt it. It's not how inheritance is supposed to work in Object Oriented Design.

If Class1 doesn't have Class2 abstract method then it shouldn't inherit from class2.

Imagine a user having a collection of class2 and calling .abstractMethod() on each and every one in it. Later someone adds a instance of Class1 to it.

Neither of these programmers did anything wrong but the code still doesn't work.

Consider adding one more level of abstract here so that top level abstract has all feature class1 and class2 have and they both inherit from it. Class2 then adds the abstractMethod.


It's a bad idea because it goes against the SOLID principle, especially the L part of the principle. If someone else was trying to use your derived class knowing that inherits from the base class which already has the method, he'd be very much confused about the incomplete implementation, especially since it's an abstract method. Interface is the way to go, as previously stated, you can define an explicit implementation and effectivelly hide the method.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号