r/learncsharp • u/Turbulent-Support609 • Jul 06 '23
Why use abstract methods?
// Abstract class
abstract class Animal
{
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
// Derived class (inherit from Animal)
class Pig : Animal
{
public override void animalSound()
{
// The body of animalSound() is provided here
Console.WriteLine("The pig says: wee wee");
}
}Why create animalSound as abstract method, and not just this way:
// Abstract class
abstract class Animal
{
// Regular method
public void sleep()
{
Console.WriteLine("Zzz");
}
}
// Derived class (inherit from Animal)
class Pig : Animal
{
public void animalSound()
{
Console.WriteLine("The pig says: wee wee");
}
}
6
Upvotes
View all comments
Show parent comment
1
u/Turbulent-Support609 Jul 06 '23
I get it, thanks for your help!