C
C#3y ago
.tree

Abstract class functions

Is it fine design wise to have an abstract class A with 2 classes B and C inheriting from it, with B just overriding the functions the abstract class offers but C having some additional functions that are neither in parent class A nor B?
11 Replies
TheBoxyBear
TheBoxyBear3y ago
If it makes sense for your model, then yes
.tree
.treeOP3y ago
Thank you. Lets say I now have a class D which shares some of the additional functions in class C. I can't add them to the abstract class because then class A would need to implement them too (which I do not want). What would the solution for this be?
TheBoxyBear
TheBoxyBear3y ago
You could define them in C and make that abstract "Implementing" would be giving a method body. In an abstract class or interface, you can define members with no implementation Define members at the highest level you want them to be shared, defining classes as abstract if it doesn't make sense to be implemented at that level
.tree
.treeOP3y ago
And then make D inherit C? My bad, I meant B would need to implement them then when I put them into A since B inherits A. But I do not want B to inherit those functions that are supposed to be specific to C and D
TheBoxyBear
TheBoxyBear3y ago
If B shouldn't have them, put them in a common class for C and D If A includes it and B includes A, B also includes it Or have it defined with no implementation in B No need to implement in B if B is itself abstract
.tree
.treeOP3y ago
This is what I mean
.tree
.treeOP3y ago
You are suggesting to put another abstract class under A that C and D inherit from? Also the desctiption of A should say "stuff A, B, C and D should have in common
TheBoxyBear
TheBoxyBear3y ago
Then D should derive from C
.tree
.treeOP3y ago
C wouldn't need to be an abstract class then, right?
TheBoxyBear
TheBoxyBear3y ago
Depends if you want instance of C to be made
.tree
.treeOP3y ago
Right, of course Thank you for your help!

Did you find this page helpful?