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.
Main advantage of inheritance is reusability of the code.
Syntax
//Example program demonstrates singular inheritance
Output
First Number: 30
Second Number: 40
Third Number: 50
Sum : 70
Main advantage of inheritance is reusability of the code.
Syntax
[Access Modifier] class ClassName : baseclassname
{
}
C# Inheritance Example
//Example program demonstrates singular inheritance
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();
}
}
}
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();
}
}
}
Output
First Number: 30
Second Number: 40
Third Number: 50
Sum : 70