Inheritance is one of the most important object-oriented programming concept. It allows you to reuse existing code thereby saves time.
When you derive a class from the base class, you derive the non-private data members &
implementation of its the methods and properties that are contained in the base class.
In the derived class, you can extend the base class implementation by overriding some of the existing implementation or add your own functionality.
C# supports single & multilevel inheritance. It doesn't directly support multiple inheritance but only by the use of an interface.
using System;
class sampleInheritance
{
public class animal
{
string name;
int size;
public void genericBehavior()
{
Console.WriteLine("Generic behavior of an animal");
}
}
public class dog:animal
{
public dog()
{
//dog class constructor
}
//base class genericBehavior public method
genericBehavior();
//specific function of the dog class
private void bark()
{
Console.WriteLine("The dog barks");
}
}
public class cat:animal
{
public cat()
{
//cat class constructor
}
//base class genericBehavior method
genericBehavior();
//specific function of the cat class.
private void mews()
{
Console.WriteLine("The cat mews");
}
}
public static void Main()
{
dog _dog = new dog();
cat _cat = new cat();
}
}
In the above example, the animal class is the base class which has generic behavioral methods. The base class is further extended to create different animal breed classes like dog & cat. The derived classes are further extended by introducing their specific behavior corresponding to their breeds.
0 comments
Post a Comment