Classes can inherit from other classes. They can gain Public/Protected Variables and Functions of the parent class. The class then acts as a detailed version of the original parent class(also known as the base class).
The code below shows the simplest of examples :
public class A {
//Define Parent Class
public A() { }
} public class B : A {
//Define Child Class
public B() { }
}
In the following program we shall learn how to create & implement Base and Derived Classes. First we create a BaseClass and define the Constructor , SHoW & a function to square a given number. Next , we create a derived class and define once again the Constructor , SHoW & a function to Cube a given number but with the same name as that in the BaseClass. The code below shows how to create a derived class and inherit the functions of the BaseClass. Calling a function usually calls the DerivedClass version. But it is possible to call the BaseClass version of the function as well by prefixing the function with the BaseClass name.
class BaseClass
{
public
BaseClass()
{
Console.WriteLine("BaseClass Constructor Called\n");
}
public void Function()
{
Console.WriteLine("BaseClass Function Called\n Enter A Single
No.");
int
number = new int();
number = Convert.ToInt32(Console.ReadLine());
number = number * number;
Console.WriteLine("Square is : " + number + "\n");
}
public void SHoW()
{
Console.WriteLine("Inside the BaseClass\n");
}
}
class DerivedClass : BaseClass
{
public
DerivedClass()
{
Console.WriteLine("DerivedClass Constructor Called\n");
}
public new void Function()
{
Console.WriteLine("DerivedClass Function Called\n Enter A Single
No.");
int
number = new int();
number = Convert.ToInt32(Console.ReadLine());
number = Convert.ToInt32(number)
* Convert.ToInt32(number)
*Convert.ToInt32(number) ;
*Convert.ToInt32(number) ;
Console.WriteLine("Cube is : " + number + "\n");
}
public new void SHoW()
{
Console.WriteLine("Inside the DerivedClass\n");
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass
dr = new DerivedClass();
dr.Function(); //Call DerivedClass Function
((BaseClass)dr).Function();
//Call BaseClass Version
dr.SHoW(); //Call
DerivedClass SHoW
((BaseClass)dr).SHoW();
//Call BaseClass Version
Console.ReadKey();
}
}