Hi,
This is an example, I'm just curious as to how it would be achieved.
I want to enable only subclasses of Animal
to be able to set the number of legs that they have, but I still want them to be able to set their own colour. Therefore, I want to restrict classes further down the hierarchy from then altering this Legs
property.
public abstract class Animal
{
public string Colour { get; protected set; }
public int Legs { get; protected set; }
public abstract string Speak();
}
public class Dog : Animal
{
public Dog()
{
Legs = 4;
}
public override string Speak()
{
return "Woof";
}
}
public sealed class Springer : Dog
{
public Springer()
{
Colour = "Liver and White";
}
}
public sealed class Chihuahua : Dog
{
public Chihuahua()
{
Colour = "White";
}
public override string Speak()
{
return "*annoying* YAP!";
}
}
For example, I want to eliminate this kind of subclass:
public sealed class Dalmatian : Dog
{
public Dalmatian()
{
Legs = 20;
Colour = "Black and White";
}
}
How would this be achieved?
I'm aware that I could stop overriding in a subclass by sealing the implementation of a function in the parent class. I tried this with the Legs
property but I couldn't get it to work.
Thanks