I’m learning C# and I have a doubt about the use of inheritance in classes and I would like that somebody could help me.
If I have some classes that inherit from a abstract class, I can declare an object of the secondary class as of the type of the primary abstract class, like this:
Animal leopard = new Mammal();
Where Mammal
is a class that inherit from the abstract class Animal
. In this case, how can I access the properties that are exclusively from Mammal
class? Look the following code for a better understanding:
static void Main(string[] args)
{
Animal leopard = new Mammal("leopard", "mammal", "yellow", 80);
Bird falcon = new Bird("falcon", "bird", "black", 300);
Fish shark = new Fish("shark", "fish", "white", 80);
List<Animal> animalList = new List<Animal>();
animalList.Add(leopard);
animalList.Add(falcon);
animalList.Add(shark);
Console.WriteLine("Name: {0}, Class: {1}, Fur Collor: {2}, Running Speed: {3} km/h.",
leopard.name, leopard.animalClass, leopard.furColor, leopard.runningSpeed);
Console.ReadLine();
}
public abstract class Animal
{
public string name { get; set; }
public string animalClass { get; set; }
}
public class Mammal : Animal
{
public string furColor { get; set; }
public double runningSpeed { get; set; }
public Mammal(string name, string animalClass,
string furColor, double runningSpeed)
{
this.name = name;
this.animalClass = animalClass;
this.furColor = furColor;
this.runningSpeed = runningSpeed;
}
}
public class Bird : Animal
{
public string featherColor { get; set; }
public double flightSpeed { get; set; }
public Bird(string nam, string animalClass,
string featherColor, double flightSpeed)
{
this.name = name;
this.animalClass = animalClass;
this.featherColor = featherColor;
this.flightSpeed = flightSpeed;
}
}
public class Fish : Animal
{
public string scaleColor { get; set; }
public double swimmingSpeed { get; set; }
public Fish(string name, string animalClass,
string scaleColor, double swimmingSpeed)
{
this.name = name;
this.animalClass = animalClass;
this.scaleColor = scaleColor;
this.swimmingSpeed = swimmingSpeed;
}
}
In this example, as all classes inherit from Animal class I could add them to an List<Animal>
, but when I try to access the properties furColor
and runningSpeed
that are exclusive for Mammal class, I’ve got a error because them don’t belong to Animal class. To where these properties gone? How could I retrieve them?
Best regards,
Fabiano.
You can declare it as Mammal leopard = new Mammal();
to have access to it. Otherwise you'd need to cast leopard
back to a mammal to retrieve them since Animal
doesn't have the properties you require.
Console.WriteLine("Name: {0}, Class: {1}, Fur Collor: {2}, Running Speed: {3} km/h.",
leopard.name, leopard.animalClass, ((Mammal)leopard).furColor, ((Mammal)leopard).runningSpeed);