How to pass an attribute of the child class through the constructor to the parent class

1

I have 3 classes

Mother class: Animal

Daughter Classes: Dog and Cat

I want to write the name attribute only when one of the objects is instantiated Gato or Cachorro .

In the parent class I have the Name attribute that can be read-only ( get )

How to pass the value ( nome attribute) of the child class to the parent class through the child class constructors?

    
asked by anonymous 28.09.2018 / 19:58

2 answers

3

From what I understand of your question, you want to have a Nome property in your Animal class with the private setter and you want to assign its value through the constructor of the child class. You can use the keyword base to call the constructor of the "parent" class.

public abstract class Animal

{
    public string Nome { get; private set; }

    public Animal(string nome)
    {
        Nome = nome;
    }
}

public class Gato : Animal
{
    public Gato(string nome) : base(nome)
    {

    }
}

Example:

class Program
{
    static void Main(string[] args)
    {

        var gato = new Gato("Miau");

        Console.WriteLine(gato.Nome);            
        Console.Read();
    }

}

Reference

    
28.09.2018 / 20:51
3

You have several wrong assumptions in the question. The first is the misuse of the term attribute . I know, everyone teaches wrong because of the plague that is UML that uses this term. Languages do not use, it does not make sense to use them.

The other is that you are thinking that a field that is in the parent class is not in the daughter or that the daughter field needs to be passed to the parent class as if the parent was something else.

It's also not clear to you what a class is and what an object is . In fact it seems that classes are isolated because this is visible in code, but they are just models. When you have the object it is one thing, the models are not present in isolation, so you do not have to move anything from one to another, everything is present in the object and just use it normally.

Maybe you should understand better What is a builder for? .

You have a example using threaded builders . Other than that the question would need to be more specific.

using static System.Console;

public static class Program {
    public static void Main(string[] args) {
        var gato = new Gato("Dener");
        WriteLine(gato.Nome);            
    }
}

public abstract class Animal {
    public string Nome { get; private set; }
    public Animal(string nome) => Nome = nome;
}

public class Gato : Animal {
    public Gato(string nome) : base(nome) {}
}

See running on .NET Fiddle . And no Coding Ground . Also put it in GitHub for future reference .

    
28.09.2018 / 20:08