07 Inheritance
07 Inheritance
▪ The derived class is the specialized class for the base class.
▪ Advantage of C# Inheritance
▪ Code reusability: Now you can reuse the members of your parent
class. So, there is no need to define the member again. So less code
is required in the class.
Syntax
Note: In Inheritance, the Child class can consume members of its Parent class as if it is the owner of those
members (except private members of the parent).
using System; class B : A
namespace InheritanceDemo {
{ static void Main()
class A {
{ B obj = new B();
public void Method1() obj.Method1();
{ obj.Method2();
Console.WriteLine("Method 1"); Console.ReadKey();
} }
public void Method2() }
{ }
Console.WriteLine("Method 2");
}
}
When we are working with Inheritance, some rules are required to be followed:
▪ In C#, the parent classes constructor must be accessible to the child class; otherwise, the
inheritance would not be possible. If a constructor is defined implicitly, then it is a public
constructor.
▪ Example:
class A
{
public A()
{
Console.WriteLine("Class A Constructor is Called");
}
public void Method1()
{
Console.WriteLine("Method 1");
}
▪ In inheritance, the child class can access the parent class members, but the parent
classes can never access any members that are purely defined in the child class.
▪ If you don't want other classes to inherit from a class, use the sealed keyword:
▪ If you try to access a sealed class, C# will generate an error:
there is one base class and one public class Accountcreditinfo //base class
derived class. {
public string Credit()
{
return "balance is credited";
}
}
public class debitinfo : Accountcreditinfo //derived class
{
public string debit()
{
Credit(); ////derived class
method
return "balance is debited";
}
}
class Animal
Use of ‘protected’ {
protected string sound = "Some sound";
access specifier }