简体   繁体   中英

(C#) How do you deal with a Base class with a constructor, when you want to make an inheriting class?

Im trying to make a Dog class, inheriting the Animal base class which has a constructor. Is there any way I can make the class Dog : Animal, but somehow use the Animal constructor with it? I looked at the similar questions, but I didnt get the answer I'm looking for.

class Class1
{       
   static void Main(string[] args)
   {
        Animal animal = new Animal("Spotty", 5, 4);
        animal.Print();
   }
}

class Animal
{
    public string animalName;
    public int animalAge;
    public int animalLegs;
    public Animal(string name, int age, int legs)
    {
        animalName = name;
        animalAge = age;
        animalLegs = legs;       
    }       

    public void Print()
    {
        Console.WriteLine("Name: " +animalName);
        Console.WriteLine("Age: "+ animalAge);
        Console.WriteLine("Number of Legs: " +animalLegs);
    }
}

class Dog : Animal
{
    //This wont work; there will be an error
}

You should either add a default constructor to Animal , or add the necessary constructor to Dog :

public Dog(string name, int age) : base(name, age, 4)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM