Class Diagram :-
Example:-
using System;
using
System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CAClasses
{
class ClsEmployee
{
int
EmpId;
string
EName;
int EAge;
string
EAddress;
public
void GetEmpData()
{
Console.WriteLine("Enter the Employee Details:-");
EmpId = Convert.ToInt32(Console.ReadLine());
EName = Console.ReadLine();
EAge = Convert.ToInt32(Console.ReadLine());
EAddress = Console.ReadLine();
}
public
void DisplayEmpData()
{
Console.WriteLine("Employee Details");
Console.WriteLine("Employee Id is:- "+EmpId);
Console.WriteLine("Employee Name is:- "+EName);
Console.WriteLine("Employee Age is:- "+EAge);
Console.WriteLine("Employee Address is:-"+EAddress);
}
}
class ClsExample
{
static
void Main(string[]
args)
{
ClsEmployee
obj1 = new ClsEmployee();
ClsEmployee
obj2 = new ClsEmployee();
obj1.GetEmpData();
obj2.GetEmpData();
obj1.DisplayEmpData();
obj2.DisplayEmpData();
Console.ReadLine();
}
}
}
|
Output
:-
- To access any members of a class, with the help of object we use (dot) operator known as Member Access Operator like Objectname.Member Name
- Using member access operator, we can access any member based on its accessibility
- When an object to a class is created, runtime will allot the memory for the members of a class and reference will be maintain from the object this will be done by new keyword / Operator
- In the above example, memory will be allotted for the members and reference will be maintained from the objects like . . . . .
- If new keyword is not used, then memory will not be allotted to the Data Fields and no reference will be maintained from the object and raises an error as Null Reference Error
- this keyword:
- this is a keyword used to access the current class in the same class.
- this is an object for the current class in the same class
How
Encapsulation is Implemented:
- In the above example when Obj1.GetEmpData( ) function is called Obj1 reference will be copied in to this keyword / Object and Obj1 referenced Data Fields will be bound to GetEmpData( )function
- When Obj2.GetEmpData( ) function is called Obj2 reference will be copied into this keyword / Object and Obj2 referenced Data Fields will be bound to GetEmpData( ) function
- Similarly for DisplayEmpData( )function also, i.e. whenever any function is called with any Object of the class that Object referenced Data Fields (Member Variables) will be bound to the respective Member Function, this feature we call as Encapsulation
No comments:
Post a Comment