Encapsulation:
Encapsulation is a process of binding the data members and member functions into a single unit.
Example
A class can contain data fields and methods.
Consider the following class
public class Aperture
{
protected double height;
protected double width;
protected double thickness;
public double get volume()
{
Double volume=height * width * thickness;
if (volume<0)
return 0;
return volume;
}
}In this example we encapsulate some data such as height, width, thickness and method Get Volume. Other methods or objects can interact with this object through methods that have public access modifier.
Inheritance:
Inheritance is a process of deriving the new class from already existing class.
There are 5 types of inheritances in C#. they are
1.Single Inheritance
2.Multilevel INheritance
3.Multiple Inheritance
4.Hybrid Inheritance
5.Hierarchical inheritance.
Single Inheritance :
when a single derived class is created from a single base class then the inheritance is called as single inheritance.
Program :
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();
}
}
}
Output
First Number: 30
Second Number: 40
Third Number: 50
Sum : 70
This comment has been removed by the author.
ReplyDelete