简体   繁体   中英

Create constructor for class that inherits from abstract class

I have an abstract class which is inherited. The class that inherits from the abstract class should have an extended constructor.

I can't find what I'm looking for on the internet because I don't know how to tell it.

My code looks like this:

My animal abstract class

public abstract class Animal : PictureBox
{
    public string name { get; }
    public int age { get; }
    public bool gender { get; }
    public Image img { get;}

    protected Animal(string name, int age, bool gender)
    {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public virtual void SayYourName()
    {
        Debug.WriteLine("My age is:", name);
    }

    public virtual void SayYourAge()
    {
        Debug.WriteLine("My age is:", age);
    }

    public virtual void SayYourGender()
    {
        if (gender == true)
        {
            Debug.WriteLine("My gender is Male");
        }
        else
        {
            Debug.WriteLine("My gender is Female");
        }
    }

    public virtual void eat()
    {
        Debug.WriteLine("I ate!");
    }

My Amphibian abstract Class

{
public abstract class Amphibian : Animal, ISwim, IWalk
{

    public void swim()
    {
        Debug.WriteLine("I swam!");
    }

    public void walk()
    {
        Debug.WriteLine("I walked!");
    }
}

My Frog abstract class

public abstract class Frog : Amphibian
{
}

My African_bullfrog class

public sealed class African_bullfrog : Frog 
{

    public African_bullfrog(string name, int age, bool gender) 
        : base(name, age, gender)
    {
        this.img = Zoo.Properties.Resources._01__African_Bullfrog;

    }

My problem happens in the last code section

All your classes that inherit from Animal must provide the information that the Animal needs, so you have to provide a constructor that takes these information and pass them to base constructor.

public abstract class Amphibian : Animal, ISwim, IWalk
{
    public Amphibian(string name, int age, bool gender):base(name, age, gender)
    {   
    }
    // ...
}

public abstract class Frog : Amphibian
{
    public Frog(string name, int age, bool gender):base(name, age, gender)
    {
    }
}

public sealed class African_bullfrog : Frog
{
    public African_bullfrog(string name, int age, bool gender)
        : base(name, age, gender)
    {
        // ...
    }
}

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