Home > Software design >  Which class do I place the fields related to an object in?
Which class do I place the fields related to an object in?

Time:09-17

Hi I'm new to OOP and I can't seem to find information on this problem I have. Any help would be great. I'm working in C#

So I have a base abstract class Animal, and a derived class Pig. I want to have other derived classes such as a cow etc. Each animal need to have a name.

Do I place the AnimalName field as protected in the base class and use base.AnimalName to access? Or should the name field belong to the derived class as a private/protected field?

My thinking is that if I have abstract methods that need to be overwritten, should be name field not follow a similar format or should it rather just be declared in the derived class.

Is there is a convention to this?

CodePudding user response:

If the attribute Name is inherent to being an Animal (every Animal must have it), then place it in the Animal abstract class, as protected, or as private with getters and setters (more common).

CodePudding user response:

An abstract class, as @Ivan describes, is a good idea. But, sometimes your namespace will actually benefit from using nested classes. Then, you can overwrite AnimalName in a similar manner.

Check out this answer for more: https://stackoverflow.com/a/10507130/14414944

Edit: Per CoolBots request, check out this C# Fiddle. There are some good nuggets there to chew on.

I would also recommend supplementing your OOP learning by reading about Composition vs. Inheritance in C#.

  • Related