0

I have an Animal class with X properties and Tiger class with B properties. The Tiger class inherits from the Animal. When I create an instance of the tiger class, how I put the arguments of the Animal class?

Thanks :)

class Program
    {
        static void Main(string[] args)
        {
            Animal dogA = new Tiger()
            dogA.Run();
            Console.ReadLine();
        }
    }
    class Animal
    {
        public int Age { get; set; }
        public string Color { get; set; }
        public float Speed { get; set; }

        public Animal(int age, string color, float speed)
        {
            Age = age;
            Color = color;
            Speed = speed;
        }
        public virtual void Run()
        {
            float runSpeed = (-1 * Speed) + 100;
            Console.WriteLine("I'm running at {0} kph", Speed);
        }
    }
    class Tiger : Animal
    {
        public int Legs { get; set; }

        public Tiger(int legs)
        {
            Legs = legs;
        }
        public override void Run()
        {
            double runSpeed = (Legs * Speed) / 2.5;
            Console.WriteLine("I'm running at {0} kph", Speed);
        }
    }
  • This is called calling the base class constructor. Look here - https://stackoverflow.com/questions/12051/calling-the-base-constructor-in-c-sharp – Stilgar Mar 10 '19 at 17:36

1 Answers1

0

change constructor in child class like

public class Tiger : Animal
{
    public int Legs { get; set; }

    public Tiger(int age, string color, float speed) : base(age,color,speed)
    {
        Legs = this.Legs;
    }
}

and then create instance from Tiger class like

   Tiger dogA = new Tiger(3, "red", 2.3f);
   dogA.Age = 12;
   dogA.Color = "Brown";
   dogA.Speed = 2.3f;
   dogA.Legs = 4;
   dogA.Run();

Result : I'm running at 3.67999992370605 kph

Saif
  • 2,611
  • 3
  • 17
  • 37
  • `Legs = this.Legs` will create an infinite loop of getting and setting the property. Instead there should be a `legs` argument in the constructor. – juharr Mar 10 '19 at 18:36