Creating a new class from existing class is called as inheritance.
When a new class needs same members as an existing class, then instead of creating those members again in new class, the new class can be created from existing class, which is called as inheritance.
During inheritance, the class that is inherited is called as base class and the class that does the inheritance is called as derived class and every non private member in base class will become the member of derived class.
If you want the base class members to be accessed by derived class only , you can apply
using System;
namespace ProgramCall
{
class BaseClass
{
//Method to find sum of give 2 numbers
public int FindSum(int x, int y)
{
return (x + y);
}
//method to print given 2 numbers
//When declared protected , can be accessed only from inside the derived class
//cannot access with the instance of derived class
protected void Print(int x, int y)
{
Console.WriteLine("First Number: " + x);
Console.WriteLine("Second Number: " + y);
}
}
class Derivedclass : BaseClass
{
public void Print3numbers(int x, int y, int z)
{
Print(x, y); //We can directly call baseclass members
Console.WriteLine("Third Number: " + z);
}
}
class MainClass
{
static void Main(string[] args)
{
//Create instance for derived class, so that base class members
// can also be accessed
//This is possible because derivedclass is inheriting base class
Derivedclass instance = new Derivedclass();
instance.Print3numbers(30, 40, 50); //Derived class internally calls base class method.
int sum = instance.FindSum(30, 40); //calling base class method with derived class instance
Console.WriteLine("Sum : " + sum);
Console.Read();
}
}
}