0

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?

  • Microsoft's [C# guide](https://learn.microsoft.com/en-us/dotnet/csharp/) offers some tutorials, including [Introduction to classes](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/classes), [Object Oriented C#](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/oop), and [Inheritance in C# and .NET](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/inheritance). The last tutorial I mentioned has a complete example of OOP structure; take a look at *Designing the base class and derived classes* section. – CoolBots Sep 05 '21 at 19:27

2 Answers2

1

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).

Iván
  • 971
  • 6
  • 20
-1

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#.

lmonninger
  • 831
  • 3
  • 13
  • Could you please clarify your answer? OP is very new to OOP (as they stated) - perhaps an example of *when* nested classes would be beneficial? The linked question is related to simulating C++ `friend` keyword in C# - not at all what OP is asking about. Also, the sentence *Then, you can overwrite AnimalName in a similar manner* requires clarification - overwrite it *where*? In the inner class? Is the inner class inheriting the outer class? Please either clarify or remove this answer. Thank you! – CoolBots Sep 05 '21 at 19:08
  • @CoolBots updated my answer, would you mind removing the down vote? – lmonninger Sep 05 '21 at 20:16
  • I removed my downvote; thanks for adding the C# Fiddle. – CoolBots Sep 05 '21 at 22:47