|
Inheritance is the ability to
define a new class or object that inherits the behavior and its functionality of
an existing class. The new class or object is called a child or subclass or
derived class while the original class is called parent or base class.
In other words when a class acquire the property of another class is known as
inheritance.We can say
that, inheritance is the second pillar of OOPs because with the help of single
class we can’t make our project.
Through inheritance we can achieve
code reusability and
encapsulation. How?
Ans – code reusability….
Here we have made a function
with name Info in class
BASE and that function performs X task.
We have one more class too named is
Derive.
Derive class wants to use base class
function.
Now, there are two methods- one
is we can create Info function again
in class Derive second is we can
simple inherited class BASE and call
Info function. This method is called
code reusability.
|
using System;
namespace inheritance
{
class
BASE
{
public void
Info()
{
Console.Write("Enter Your Name...");
string
name=Console.ReadLine();
Console.Write("Enter Your Address...");
string add =
Console.ReadLine();
Console.WriteLine(name);
Console.WriteLine(add);
Console.ReadLine();
}
}
class
Derive:BASE
{
static void
Main(string[] args)
{
Derive d =
new Derive();
d.Info();
}
}
}
|
Ans – Encapsulation…
When we inherited base class in
derived class and call the function of base class through derived class object, but in background base
class object is made, and that base class object call the function.
In other words we can say that
when we calling function via dot operator that time we would not identify which
function are related to Which class .

This is called encapsulation in
term of inheritance.
Note: 1. Base class scope is always is greater than derived class scope.
2. Base
class constructer called before derived class.
3.
When we make derived class of base class than three point we see of OOPs
1. Encapsulation
2. Polymorphism
3. Abstract/ Reusability
4.
Inheritance default behavior is early binding.
Example-
|
public class Base
{
public
Base()
{
Console.WriteLine("Base Class Constructor.");
}
public
void output()
{
Console.WriteLine("I'm a Base Class.");
}
}
public class
Derive : Base
{
public
Derive()
{
Console.WriteLine("Derive Constructor.");
}
public
static void Main()
{
Derive d = new
Derive();
d.output();
}
}
|
Output:
Base
Constructor.
Derive Constructor.
I'm a Base Class.
|