I have created in my 'main' method an object 'spot' of my base class animal were are 4 properties, a 'Animal' class constructor and a function 'SaySomething'. My object 'spot' passes his parameters to the class constructor 'Animal' for initialization. Furthermore, I have created a derived class 'Dog' which is inheriting the base class 'Animal' properties and the method, and I have created an object 'grover' in my 'main' method, and when I try to access with my 'grover' object the method 'SaySomething' which was inherited, my program throws an exception: 'ConsoleApplication1.Animal' does not contain a constructor that takes 0 arguments, when I try to run the program.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Animal
{
public double height { get; set; }
public double weight { get; set; }
public string sound { get; set; }
public string name { get; set; }
public Animal(double height, double weight, string name, string sound)
{
this.height = height;
this.weight = weight;
this.name = name;
this.sound = sound;
}
public void SaySomething()
{
Console.WriteLine("{0} is {1} inches tall, weighs {2} lbs and likes to say {3}", name, height, weight, sound);
}
}
class Dog : Animal
{
}
class Program
{
static void Main(string[] args)
{
Animal spot = new Animal(16,10,"spot","woof");
Dog grover = new Dog();
grover.SaySomething();
}
}
}
I understand that I need to delete my class constructor and spot object parameters and arguments that the program could run. But what is wrong with this code? why my program can't run? And need I choose a different initialization way or it is possible to improve this code for working?
Because you don't provide any constructor for Dog
, it automatically creates an "empty" constructor, that also tries to call the Animal
"empty" constructor. You need to implement a constructor for Dog
, or an empty constructor for Animal
.