C # Inheritance
C # Inheritance
Definition
class A
{
Members
}
class B:A
{
Consuming of members of A
}
Note: In inheritance child class can consume members of its parent class as if it
is the owner of those members (except private members of parent).
Rules:
Example: Class1.cs*
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InheritanceDemo
{
class Class1
{
public Class1()
{
Console.WriteLine("Class1 Construtor is called.");
}
public void Test1()
{
Console.WriteLine("Method 1");
}
public void Test2()
{
Console.WriteLine("Method 2");
}
}
}
Class2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InheritanceDemo
{
class Class2 : Class1
{
public Class2()
{
Console.WriteLine("Class2 Construtor is called.");
}
public void Test3()
{
Console.WriteLine("Method 3");
}
static void Main()
{
Class2 c = new Class2();
c.Test1();
c.Test2();
c.Test3();
Console.ReadLine();
}
}
}
output:
2. In inheritance child class can access parent classes members but parent classes
can never be accessed any member that is purely defined under the child class.
Example: Class1.cs*
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InheritanceDemo
{
class Class1
{
public Class1()
{
Console.WriteLine("Class1 Construtor is called.");
}
public void Test1()
{
Console.WriteLine("Method 1");
}
public void Test2()
{
Console.WriteLine("Method 2");
}
}
}
Class2.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InheritanceDemo
{
class Class2 : Class1
{
public Class2()
{
Console.WriteLine("Class Construtor is called.");
}
public void Test3()
{
Console.WriteLine("Method 3");
}
static void Main()
{
Class1 p = new Class1();
p.Test1();
p.Test2();
Console.ReadLine();
}
}
}
Output:
3. We can initialize a parent classes variable by using the child class instance to
make it as a reference. So that the reference will be consuming the memory of child
class instance, but in this class also we can't call any pure child class members
by using the reference.