SlideShare a Scribd company logo
Object Oriented Programming - මූලික සංකල්ප
විදුසරට මා ලියූ ලිපි පපළ
[2011 – 2012]
පරිගණක වලින් වැ ඩගන්න ඉන්න දුවා පුතා ලා පවනුවනි!
තුති:
මෙවන් මේ ඔබ මවනුවන් ලියා පළ මෙරුෙට උදව් ෙරපු හැ ෙට!
මූලිෙ සිේධා න්ත ො හට යළිත් ෙතක් මෙරුවා වූ සියලුෙ මූලා ශ්‍රයන්ට!
OOP සර඼ල.... ඳරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
ඳසුගිය කා඼නේ විදුසර හරහා මම ඔබට C ඳරිගණක
භාෂානේ මූලික සද්ධාේත කියා දුේ ලිපි නඳළක් නගන ආ
බල ඔබට මතක ඇති. නේ ලිපි නඳලිේ අපි අදහස්
කරේනේ මෘදුකාංග ඉංජිනේරු ක්නෂේත්රනේ ලැඩිපුරම
භාවිතා ලන Object Oriented Programming
(OOP) සංකල්ඳය ගැන සර඼ල කියා දීමයි. ලර්තමානනේ
නබොනහෝ සංකීර්ණ ඳරිගණක භාෂා (High Level
Languages) නමම OOP සංකල්ඳයට අනුකූ඼ න඼ස
සකසා තිනබනලා. (උදා: C++, Java, C#, VB.Net)
නේ ලිපි නඳනළහි උදාහරණ දැක්වීම ස඲හා මම නයොදා
ගේනේ C# ඳරිගණක භාෂාලයි.
Object Oriented Programming සංකල්පය තුළින්
කකකෙන්කන් අකේ දෛනික ජීවිතය හෙහා ක ොඩ නැගී
ඇති සංකල්පයන් පරි ණක වැඩසටහන් කෙණයට ක න
ඒමයි. ඕනම වස්තුවක් Object එකක් කෙස සෙකා
වැඩසටහන් සැකසීම කමහි ඇති ම෕ලිකම ෙක්ෂණයයි.
කහොඳයි, Object Oriented Programming සංකල්පය තුළ
ඇති ප්ර්ධාාන ේෂiණ මම පහත කකාෙයට කපන්වන්නම්.
1. ABSTRACTION
ABSTRACTION යනු Design Technique
එකකි. Object Oriented Programming
සංකල්පය තුළ, වස්තුවක (Entity) සංකීර්ණ
භාවය ෙඝු කකොට ෛැක්වීමට කමය කයොෛා ැකන්.
තවදුෙටත් එය පැහැදිලි කළකහොත්, වස්තුවක
සංකීර්ණ ේෂiණ අත්හැෙ වැඩසටහන් කකොටසට
අෛාළ ෙක්ෂණ පමණක් කතෝො ැනීම මින්
අෛහස් කකකර්. මම එය ඉංග්රී සියෙකයන් කමකෙස
ෛක්වන්නම්. Abstraction is an important
technique to simplify a complex situation to
an understandalbe situation.
How ABSTRACTION used in OOP
එක් සංකීර්ණ වස්තුවක් සඳහා අෛාළ වන
ABSTRACTIONS කීපයක් තිබිය හැකිය.
කමහි මීළඟට ෛකවා ඇති ර෕ප සටහන බෙන්න.
Salesman යන යන කුෙකය තුලින් බිහි වී ඇති
abstractions කෛකක් කේනවා ඇති. (එකක්
Medical Database System එකක භාවිතා
කිරීමට සුදුසු අතෙ අකනක Sales Tracking
System එකක භාවිතා කිරීමට සුදුසුය.)
කමහි ඇති වැෛ ත්ම කරුණ වන්කන් කිසියෙයම් ෙඝු
කිරීමකට (A given abstraction) අෛාළව ඔබ කයොෛා
න්නා විචෙ(න් සහ ්රිnයාවන් (Attributes and
Behaviors) ඔබ විසියෙන් නිර්ණය කිරීමයි. එය ඔබ ඔකේ
Program එකට කහෝ Project එකට අෛාළව කයොෛා ත
යුතුයි.
Salesman යන ප්ර්ධාාන කුෙකයට අෛාළ කපොදු ෙක්ෂණ සහ
්රිnයාවන් තිකබන අතෙ Medical Database System එකට
කහෝ Sales Tracking System එකට කහෝ අෛාළ Salesman
සඳහා පමණක් අෛාළ ෙක්ෂණ සහ ්රිnයාවන් තිකබනවා.
(ඉහත සටහකනන් ෛැක්කවන්කන් එයයි.)
ABSTRACTION නිර්ණායකය, Attributes(඼ක්ෂඉණ)
Behavoirs(ක්රියයාලේ) යන කරුණු කෛකටම බෙපායි.
Attributes Behaviours ැන පහත ෛක්වා ඇති සටහන
ඉතා වැෛ ත්.
Attributes refer to the properties or characteristics
associated with an entity and Behaviors refer to the
set of actions that the entity can perform.
පහත සටහන ඔබට මා කී කෛය මනාවට පැහැදිලි කෙයි.
වැඩසටහන්කෙණකේදී Attributes නිර෕පණය වන්කන්
Data න඼සත් Behaviors නිර෕පණය වන්කන් Methods
කෙසත්ය. Data වෙට උෛාහෙණ කෙස variables, arrays,
complex data structures යනාදිය සැෙකිය හැකි අතෙ
Methods උෛාහෙණ කෙස operations, functions,
procedures සැෙකිය හැකිය.
ලැදගත්: Object Oriented Programming සංකල්පය තුළ
ක්රගමානුක෕ෙව සැකසුනු Classes, Objects, Interfaces වැනි
අං යන් විවිධා Abstractions නිර෕පණය කෙනවා.
2. CLASSLS
ඔබට මතක නම්, මම C පරි ණක භාෂාකේ ම෕ලික
සියෙද්ධාාන්ත කියාදුන් ලිපි කපකළේ, Structures නමැති
කකෘතියක් කියා දුන්නා; C පරි ණක භාෂාකේ ක,
ෛත්ත හා නිර෕පිත-්රිnයාවන් (Data & Methods) එකට
කකොට සැකසුනු කකෘතියට සමානම කකෘතියක් තමයි
Object Oriented Programming තුළ Classes
නිර෕පණය කෙන්කන්.
Classes තුළ ක ොනු කෙන්කන් කුමක් කහෝ දී තිකබන
Abstraction එකකට අෛාළ ෛත්ත, ්රිnයාවන් සහ ඒ
්රිnයාවන් සැකසී ඇති අයුරුයි. (A class derives the
specific structure of a given abstraction, like what
data it has, what methods it has and how the
methods are implemented.)
Class එකකින් එයින් නිර෕පිත සියෙයලුම Entities
නිකයෝජනය කෙයි. මම එය තවදුෙටත් පැහැදිලි
කකළොත්, Salesman Class එක Medical Database
System එකක් සහ Sales Tracking System එකක්
යන කෛකක්ම සියෙටින Salesmanව නිකයෝජනය
කෙයුතුය. Class is used to represent all the
members of a given group/class.
2.1 OBJLCTS
ෛැන් ඔබ ෛන්නවා, Class එකකින් එක සමාන
Entities කීපයක් නිර෕පණය කෙන බව. (A class
defines the structure of entire collection of
similar things. e.g: Anyone who is a Salesman)
නමුත් ෛැන් ඔබට ප්ර්ශ්්නයක් තිකබන්නට ුළුවවන්
කකොකහොමෛ අපි Class එකකින් නිර෕පිත එකම
කුෙකයකට අයත් කවනස් ති ේෂiණ සහ හැසියෙරීම්
ඇති කද්වල් කවන කෙ න්කන් කියො. ඒ සඳහා
තමයි Objects නමැති සංකල්පය හඳුන්වාදී
ඇත්කත්. An object defines a specific instance
of a class. e.g. A salesman whose name is
Nimal and has a commision rate of 10%.
Objects වලින් කකකෙන්කන් Class එකකින්
නිර෕පිත කපොදු ෙක්ෂණ සහ හැසියෙරීම් ඇති කද්වල්
වෙ විකශ්ේෂිත කමොකහොතක් නිර෕පණය කිරීමයි.
උෛහෙණයක් කෙස, Sales Tracking System
එකක්, ඉන්න නිමල් නමැති, කකොමිෂන් අනුපාතය
10% ක් කෛන salesmanව අපට එක Object
එකකින් නිර෕පණය කළ හැකිය. පහත ර෕ප සටහන
එය මනාවට කපන්වනවා.
මීළඟ කකොටස ෙබන සතිකේ.........
OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
ඳසුගිය සතිය සමග සම්බන්ධයි......
CLASSES & OBJECTS with EXAMPLES
පසුගිය සතිනේ ලිපිනේ අලසානනේ අපි කතා කනේ
Classes සහ Objects ගැනයි. නේ සතිනේ අපි ඒ
සංකේප නෙක උොහරණ ඔස්නසේ නේරුේ ගනිමු.
උොහරණය -1
අපි ගිය සතියේ කතා ක඼ Salesman Class එක ගැන
සිතමු. දී තිබුන දත්ත අනුල එය ඳහත ආකාරයට යගොඩ
නැගිය හැකිය. C# ඳරිගණක භාෂාලට අනුලයි මම
උදාහරණ යඳන්ලන්යන්. (Coding Syntaxes are
according to C#). නෙෙ ලිපි නපළ අලසේ වූ පසු ෙෙ
ඔබට පිළිබඳල සර඼ල මූලික අඩිතා඼ෙක් ලැනටන පරිදි
ලිපි නපළක් නගන එේනේ. එවිට ඔබට Coding
Syntaxes ගැන තලදුරටේ ෙැනගත හැකියි....
using System;
class Salesman
{
//These are attributes
private String name;
private double commisionRate;
private int carsSold;
// This is a constructor
public Salesman(String name)
{
this.name = name;
}
//Methods can be like this
public double calcComissionRate()
{
return (commisionRate * 12);
}
}
උොහරණය -2
අපි තලත් උදාහරණයක් බ඼මු.
Planet Class එක යගොඩනගන්යන් යකොයහොමදැයි
බ඼මු. එහි Attributes ය඼ස Name, Radius,
Gravity යන ඼ක්ෂණ යඳළ ගසා තියබනලා.ඳහත
ආකාරයට අපිට C# ල඼ Planet Class එක සැකසිය
හැකිය.
using System;
class Planet
{
private string name;
public int radius;
public double gravity;
// Constructor wihtout arguements
public Planet()
{
Console.WriteLine("Constructor
called!");
}
// Constructor wiht arguements
public Planet(int r, int g, string
n)
{
radius = r;
gravity = g;
name = n;
}
}
ඉහත Class එයකහි දැක්යලන ඳරිදි Class එයකහි නමින්ම
ඇති Methods ල඼ට අපි Constructors යැයි කියමු. ඒලා
යයොදාගන්යන් Class එයකහි Attributes initialize
කරගන්නටයි. ඒ ගැන අපි ඳසුල ඉයගන ගනිමු.....(ඉදිරි ලිපි
ලලින්)
උොහරණය -3
Simple Animal Class එකක් යගොඩ නගමු. එහි විවිධ
methods තිබිය හැකිය.
අදාළ C# Class එක:
using System;
class Animal
{
string type;
int size;
float speed;
int strength;
//Constructor
public Animal()
{
Console.WriteLine("Animal
constructor");
}
//Methods...
public void Greet()
{
Console.WriteLine("Animal says
Hello");
}
public void Talk()
{
Console.WriteLine("Animal
talk");
}
public virtual void Sing()
{
Console.WriteLine("Animal
song");
}
};
යහො඲යි දැන් අපි බ඼මු යකොහමද යම් Classes ල඼
instances, එයහමත් නැත්නම් Objects නිර්මාණය
කරන්යන් කිය඼ා. අපි ඊට යයොදාගන්යන් new Operator
එකයි. (C++, Java & C# all uses this “new” operator
to declare and initialize objects of classes.)
අපි බ඼මු යකොයහොමද ඉහත නිර්මාණය ක඼ Classes
තුයන් Objects හදා ගන්යන් කිය඼ා....ඒ ස඲හා මම
යයොදාගන්යන් Main program එකයි. C# ල඼ ප්රගධාන
Method එක ඇති Class එක අපි Program Class එක
ය඼ස හඳුන්ලනලා. Programs Run කරන්නට අපිට යම්
Class එක ඕයන් යලනලා. දැන් ඳහත ඇති Object
Delcarations සහ Initialization යහොඳින් බ඼න්න......
using System;
namespace TestingClasses
{
class Program
{
static void Main(string[]
args)
{
//Objects of Salesman
Class
Salesman sm1 = new
Salesman("Nimal");
Salesman sm2 = new
Salesman("Mapa");
//Objects of Planet Class
Planet p1 = new Planet();
Planet p2 = new Planet();
//Objects of Animal Class
Animal a1 = new Animal();
Animal a2 = new Animal();
Console.ReadKey();
}
}
}
යම් ඳාඩම සර඼ කරන්නට මම එකම Project එයක් යම්
Classes සියල්඼ම යයෝදාගත්තට, සැබෑ Programming
ල඼දී ඒ Project එකට අදාළ Classes ඳමණයි
යයොදාගන්යන්. Salesman, Planet & Animal classes
are relevant to different projects. But to
demonstrate I have used all of them in one program
class.
මීළඟ යකොටස ඼බන සතියේ.........
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
ඳසුගිය වතිය වමග වම්බන්ධයි......
‘new’ OPERATOR
ඳසුගිය ලිපියේ අලවානයේ අපි කතා කයේ Classes ල඼
Objects ගැනයි. යම් වතියේ මුලින්ම අපි, Classes ල඼
Objects ශදන්නට යයොදා ගත්, new Operator එක කරන
කාර්යය යත්රුම් ගනිමු.
යමම new operator එක, අලුත් Object (Instance) එක
ව඲ශා අල඾w මතකය යලන් කරන අතර අදාෂ Class
එයේ නියමිත Constructor එක වම්බන්ධ කරගැනීම ද
එයින් ඼බායදන Reference එක Object(Instance) එකට
඼බා දීම ද කරනලා...
‘new’ operator does,
 Memory allocation for the new instance
 Invoking of the constructor to initialize the
new instance
 Returning of a reference to the instance
CONSTRUCTORS
Constructor එකේ යනු, Class එකක Object එකේ
එයශමත් නැත්නම් Instance එකේ Initialize කරන්නට
යයොදා ගන්නා විය඾ේ඿ Method එකකි. ඔබ විය඾ේ඿යයන්ම
මතක තබා ගත යුතු කරණයේ ලන්යන්, යමම
Constructors යයොදා යනොයගන ඔබට Class එකක
Object එකේ ශදන්නට යනොශැකි බල...
Constructors ල඼ ප්රහධාන ඼ේ඿ණ කිහිඳයේ ඳශත
දේලන්නම්:
 එහි නම Class
එයේ නමම විය යුතුය
.
 එහි Return Type එකේ තිබිය යනොශැකිය.
 Default Constructor:
o Parameters නැති Constructor එක
Default Constructor එක ය඼ව
Compiler එක ශඳුනාගනී.
o ඔයේ Class
එයේ Constructor එකේ
යනොමැති නම්, Run Time එයේදී
Compiler එක Default Constructor
එක නිර්මාණය කරගනී.
o Contructors ල඼ට Access Modifiers
භාවිතා කෂ ශැකිය.
Constructors වලට උදාහරණ-1:
public class MySimpleClass
{
public MySimpleClass()
{
Console.WriteLine(“Default ”);
}
}
ඉශත දේලා ඇති MySimpleClass() නමැති
Constructor එක, Default Constructor එක ය඼ව
Compiler එක ශඳුනාගනී.
Constructors වලට උදාහරණ-2:
public class MySimpleClass
{
public MySimpleClass(int x)
{
Console.WriteLine(x);
}
}
ඉශත දේලා ඇති MySimpleClass() නමැති
Constructor එකට, එේ Parameter එකේ තියබනලා. එම
නිවා අපි එලැනි Constructors ල඼ට Constructor with
Parameters යැයි කියනු ඼බනලා. එලන් අලව්ථා ල඼දී, යම්
Constructor එක භාවිතා කර Object එකේ Initialize
කරනලානම්, අපි Integer Parameter එකේ ද එවිය යුතුයි.
නිදර්඾නයකින් යඳන්ලනලානම්:
MySimpleClass mySimpleObject = new
MySimpleClass(10);
ය඼ව අඳට Program Class එනකහි
mySimpleObject Object එකේ Initialize කරගත
ශැකිය. යම් උදාශරණයේ ආකාරයට Main Program එක
Run කෂාම, Console එයකහි (Outputs යඳන්ලන Screen
එක) 10 print යලයි...
CONSTRUCTOR OVERLOADING
එකම Class එයකහි විවිධ Parameters(Arguements)
වහිතල Constructors තිබීම යමය඼ව ශඳුන්ලනු ඼ැයේ.එේ
එේ Constructor එයකන් කරන කාර්යය යලනව් යේ.
ඳශත උදාශරණය බ඼න්න:
using System;
namespace TestingClasses
{
class Box
{
int length; //Attributes of the
Box class
int width;
int height;
//Constructor with one parameter
public Box(int l)
{
length = l;
width = l;
height = l;
}
//Constructor with three
parameters
public Box(int h, int w, int l)
{
length = l;
width = w;
height = h;
}
}
}
Box Class එයකහි Constructors යදකේ overload වී
ඇත. ඔබ Box instance එකේ වැදීමට භවිතා කරන
Constructor එක අනුල එහි Outcome එක ඼ැයබයි. අපි
හිතමු ඔබට ඝනකයේ Initialize කරගත යුතුයි
කිය඼ා...එවිට ඳාවිච්චි කෂ යුත්යත් Arguement එකේ
ඇති Constructor එකයි. එය ඳශත දැේයලන ය඼ව
ක඼ ශැකියි.
Box myBox1 = new Box(10);
හිතමු ඔබට ඝනකාභයේ Initialize කරගත යුතුයි
කිය඼ා...එවිට ඳාවිච්චි කෂ යුත්යත් Arguement තුනේ
ඇති Constructor එකයි. එය ඳශත දැේයලන ය඼ව
ක඼ ශැකියි.
Box myBox2 = new Box(3, 4, 5);
CONSTRUCTOR CHAINING
එක Constructor එකේ තල Constructor එකේ call
කිරීම යමය඼ව ශැඳින්යේ...එය ඳැශැදිලි වීම ව඲ශා
ඳශත නිදර්඾නය බ඼මු.
using System;
namespace TestingClasses
{
class Box
{
int length;
int width;
int height;
/*Constructor with three
parameters*/
public Box(int h, int w, int l)
{
length = l;
width = w;
height = h;
Console.WriteLine(l + " " +
w + " " + h + "n");
}
/*Although this has a constructor
chaining this is still a constructor
with 1 parameter.*/
public Box(int len) : this(len,
len, len)
{
}
}
}
Program Class එයකහි Instances ශැයදන ආකාරයට
Main Program එයකන් ඼බායදන Output එක යලනව්
ලන අයුරින් ඔබට ඉශත දී මා කියූ යේ ලැටයශේවි.
Box myBox1 = new Box(10); ය඼ව
Initialize කෂයශොත් ඼ැයබන Output එක:
Box myBox2 = new Box(3, 4, 5); ය඼ව
Initialize කෂයශොත් ඼ැයබන Output එක:
මීෂඟ යකොටව ඼බන වතියේ.........
OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
ඳසුගිය සතිය සමග සම්බන්ධයි......
Static & Non-Static Context
තලමත් අඳ සිටින්නන් OOP හි Classes & Objects යන
සංකල්ඳනේමයි. නම් ලිපිය තුළ අපි සාකච්ඡා කරන්නන්
Static (ස්ථීර) සහ Non-Static (අස්ථීර) විච඼ යන්
ගැනයි. C# භාෂානේ ලනේම Java ල඼දීත් ස්ථීර
විච඼ යන් හැිනන්ීමම “static” යන key-word එක
නයොදා ගැනනනලා. Class එකක static variables
නයොදාගැනනන ආකාර අපි උදාහරණ නදකකින් ඉනගන
ගනිමු. (උදාහරණ තුළින් අලනබෝධ කර ගැනීම, ම෕඼ධර්ම
හරි හැටි ල හාගන්න ඉතාම ලැදගත්.)
උදාහරණය-1:
Static variable එකක් සහිත ඳහත දක්ලා ඇති Box
Class එක අධ නය කරන්න.
using System;
namespace TestingClasses
{
class Box
{
//Non static fields
int length;
int width;
int height;
//Static field
static int noOfBoxes = 0;
//Constructor with three
parameters
public Box(int h, int w, int
l)
{
length = l;
width = w;
height = h;
Console.WriteLine("nBox
constructor with 3 parameters
called!n");
Console.WriteLine("Height
of the Box = " + h);
Console.WriteLine("Width
of the Box = " + w);
Console.WriteLine("Length
of the Box = " + l);
noOfBoxes++;
Console.WriteLine("No. of
Boxes created until now = " +
noOfBoxes);
}
}
}
දැන් අපි බ඼මු නම් Class එනක් Instances හදා නගන
මුලින් ස඲හන් ක඼ Static variable එනකන් ලැඩක්
ගන්නන් නකනසේද කියා...ඒ ස඲හා අඳ Program Class
එක තුළ ලැඩස හන ලියන්න නලනලා...මීළඟ දක්ලා
ඇත්නත් ඒ Class එකයි. (නමම පිටුනේ තීරු ල඼ ඉඩ
100% ක්ම ඳරිහරණය ක඼ යුතු නිසා සමහර Coding
Lines අදාළ නේළිනයන් ඉලත්ල ඊළඟ නේළිය නගොස්
ඇත...(Microsoft Visual Studio – C# ල඼ ඔබ නම්
උදාහරණ type කර බ඼න්න)
using System;
namespace TestingClasses
{
class Program
{
static void Main(string[] args)
{
Box myBox1 = new Box(10,
10, 20);
Box myBox2 = new Box(3, 4,
5);
Box myBox3 = new Box(12,
12, 12);
Console.ReadKey();
}
}
}
Box Constructor එක call නලන හැම අලස්ථාලකම
අනේ static variable එක (noOfBoxes) එකකින්
ලැඩි නලනලා. (නමය සිදුලන්නන් Box Constructor
එක ඇතුනල් noOfBoxes හි ඒ නමොනහොනත් අගය,
එකකින් ලැඩි කරන නිසයි. noOfBoxes++ න඼ස
දක්ලා ඇත්නත් එයයි.)
ඉහත ලැඩස හනන් Output එක ඳහත ඳරිදි ඔබ
දිස්නේවි:
ඔබ නඳනනනලා ඇති Box Constructor එක call
නලන ලාරයක් ඳාසාම noOfBoxes variable එක
එකකින් ලැඩිීම, එනතක් create ීම ඇති Box Objects
ගණන නඳන්ලන බල. නම් නේ නමන඼ස ක඼ හැක්නක්,
noOfBoxes variable එක static වුනු නිසයි.
අපි දැන් static variable එක non-static කර බ඼මු.
නලනත් විදිහකින් කිේනලොත්, noOfBoxes variable
එක අනනක් non-static variables ලනේම හසුරලනලා.
අපි ඒලා Instance variables න඼සද හඳුන්ලනලා.
මක්නිසාද, ඒලා (non-static) එක Instance එකක
ඳමණක් නයොදා ගැනනන නිසා.
ඳහත උදාහරණය තුළින් ඔබ Static & Non-Static
සංකල්ඳය නහොිනන් ල හා ගත හැකිය.
උදාහරණය-2:
using System;
namespace TestingClasses
{
class Box
{
//Non static(Instance)
Variables
int length;
int width;
int height;
int noOfBoxes = 0;
//Constructor with three
parameters
public Box(int h, int w, int
l)
{
length = l;
width = w;
height = h;
Console.WriteLine("nBox
constructor with 3 parameters
called!n");
Console.WriteLine("Height
of the Box = " + h);
Console.WriteLine("Width
of the Box = " + w);
Console.WriteLine("Length
of the Box = " + l);
noOfBoxes++;
Console.WriteLine("No. of
Boxes created until now = " +
noOfBoxes);
}
}
}
කලින් නයොදාගැනුණු Program Class එකම නමහිදීත්
නයොදාගන්න පුළුලනි. එවි ඼ැනබන Output එක ඳහත
ඳරිදි ඔබ දිස්නේවි:
නෙහිදී, noOfBoxes variable එක static
න ොවුණු නිසා, පළනලනි Box Object එක හැදුනු පසුල
noOfBoxes හි අගය එකකිේ ලැඩි වු ත් ඉේ
අ තුරුල එහි ලැඩි වීෙක් නපේලේනේ ැහැ. නකොතරම්
Box Objects හැදුනත්(නකොතරම් Box Constructor
එක call වුනත්) noOfBoxes හි අගය ඳළනලනි
Constructor call එනකන් ඳසු එන අගයමයි
නඳන්ලන්නන්. නහො඲යි, නම් ලිපිනයන් ඔබ Static & Non-
Static Context එක ගැන අලනබෝධයක් ඼බාගන්න
ඇතැයි සිතනලා.
මීළඟ නකො ස ඼බන සතිනේ.........
OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
METHODS
තලමත් අප රැදී ඉන්නන් OOP හි Classes & Objects
යන වංකල්පනේමයි. නේ ලිපියන් අපි වාකච්ඡා කරන්නන්
Classes ල඼ භාවිතා ලන METHODS ගැනයි.
Classes තුෂ ඊට අදාෂ ක්රිනයාලන් ඉටු කරගැනීමට අපි
METHODS නයොදා ගනිමු.
METHOD Declaration syntax: (නපොදුනේ method
එකක් අර්ථ දක්ලන ආකාරය)
[Visibility] ReturnType MethodName([parameters])
උදාහරණ:
 public int CalculateTotal(int
x, int y)
 public double GetVolume()
 public void
Celcius_to_Farenheight();
Note: Constructor එකක් යනු වින඾ේ඿ method එකක්
බල දැන් ඔබට අලනබෝධ නලනලා ඇති.
අපි අද ලිපිනයන් method ල඼ට සර඼ උදාශරණ
කිහිපයක් බ඼මු:
උදාහරණය -1
Calculator.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace TestingMethods
{
class Calculator
{
double sum, diff, mul = 0;
float div = 0;
/*Default Constructor*/
public Calculator()
{
}
/*This method calculates &
prints the sum of the two input
varialbes*/
public void CalculateSum(int
a, int b)
{
sum = a + b;
Console.WriteLine("n* Sum
of the two variables: " + sum);
}
/*This method calculates &
prints the difference between the two
input varialbes*/
public void CalculateDiff(int
a, int b)
{
diff = a - b;
Console.WriteLine("n*
Difference of the two variables: " +
diff);
}
/*This method calculates &
prints the multiplication of the two
input varialbes*/
public void CalculateMul(int a,
int b)
{
mul = a * b;
Console.WriteLine("n*
Multiplication of the two variables: "
+ mul);
}
/*This method calculates &
prints the division between the two
input varialbes*/
public void CalculateDiv(int a,
int b)
{
div = a / b;
Console.WriteLine("n*
Division of the two variables: " +
div);
}
}
}
Program.cs:
using System;
namespace TestingMethods
{
class Program
{
static void Main(string[] args)
{
int x = 20, y = 10;
Calculator myCalc = new
Calculator();
//Find the Addion
myCalc.CalculateSum(x, y);
//Find the Difference
myCalc.CalculateDiff(x, y);
//Find the Multiplication
myCalc.CalculateMul(x, y);
//Find the Division
myCalc.CalculateDiv(x, y);
Console.ReadKey();
}
}
}
Output of this program:
උදාහරණය -2
Sphere.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace TestingMethods
{
class Sphere
{
public Sphere()
{
}
public double ReturnArea(double
radius)
{
return (radius * radius *
3.14285714);
}
public double
ReturnVolume(double radius)
{
return (4 * 3.14159 * radius
* radius * radius / 3);
}
}
}
Program.cs:
using System;
namespace TestingMethods
{
class Program
{
static void Main(string[] args)
{
Sphere mySpehre = new
Sphere();
Console.WriteLine("nInput
the radius of your sphere: ");
double rad =
Convert.ToDouble(Console.ReadLine());
Console.WriteLine("nYour
Sphere Characteristics");
Console.WriteLine("---------
------------------n");
Console.WriteLine("Radius :
{0}", rad);
Console.WriteLine("Area :
{0}", mySpehre.ReturnArea(rad));
Console.WriteLine("Volume :
{0}", mySpehre.ReturnVolume(rad));
Console.ReadKey();
}
}
}
Output of this program:
OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
ඳසුගිය වතිය වමග වම්බන්ධයි......
METHODS තල දුරටත්.........
මම් ලිපියන් අපි වළකච්ඡළ කරන්මන් ඳසු ගිය වතිමේ
ලමේම Classes ල඼ භළවිතළ ලන METHODS ගෆනයි.
අදත් අපි METHODS ල඼ට උදළශරණ කිහිඳයක්
බ඼මු. ඔබ මම් උදළශරණ Visual C# භළවිතළ කර Type
කර Run කර බ඼න්න. මම් වතිමයත් මම උදළශරණ
මගන එන්මන් ඔබට මම් වංකල්ඳ (විම඾ේ඿මයන් මම් ලිපි
මඳෂ ශරශළ අලුමතන්ම Object Oriented Programming
ඉමගන ගන්නළ අයට) වර඼ල වශ මශොඳින් අලමබෝධ වීම
ව඲ශළයි. ඔබට මළ කලින් ව඲ශන් ක඼ ඳරිදි,
METHODS ලලින් කරන්මන්, ඳරිගණක
ලෆඩවටශකින් බ඼ළමඳොමරොත්තු ලන ක්රිනයළලන් ඉ
කිරීමයි. ඒ ව඲ශළ ඔබ නිලෆරදිල අදළෂ METHODS,
අදාළ CLASS එමක් ලිවිය යුතුයි. අපි අද මුලින්ම
මවල්සියවහ උ඿හණත්ලයක් සෆරන්ශයිට් ල඼ට ශරලන වර඼
METHOD එකක් බ඼මු. මමය ලියළ ඇත්මත්
Program.cs නෆතමශොත් Main Program එක ඇති ප්ර ධළන
Class එක තුෂමය.
උදාහරණය -3
using System;
class Program
{
static void Main()
{
Console.WriteLine("This program
converts Celsius To Fahrenheit");
Console.WriteLine("----------------
---------------------------n");
Console.WriteLine("{0} ==> {1}",
100,
ConvertTemp.ConvertCelsiusToFahrenheit(100)
);
Console.WriteLine("{0} ==> {1}",
212,
ConvertTemp.ConvertFahrenheitToCelsius(212)
);
Console.WriteLine("{0} ==> {1}",
50,
ConvertTemp.ConvertCelsiusToFahrenheit(50))
;
Console.WriteLine("{0} ==> {1}",
122,ConvertTemp.ConvertFahrenheitToCelsius(
122));
Console.ReadKey();
}
static class ConvertTemp
{
public static double
ConvertCelsiusToFahrenheit(double c)
{
return ((9.0 / 5.0) * c) + 32;
}
public static double
ConvertFahrenheitToCelsius(double f)
{
return (5.0 / 9.0) * (f - 32);
}
}
}
මීෂඟ උදළශරණය මළ මගන එන්මන් විවිධ Parameters
භළවිතළ කර Methods ලියන ආකළරය මඳන්ලන්නටයි.
මමහි එක MethodParams class එක තුෂ ඇති අතර
Address වශ MethodParams යන classes මදකම
ඇත්මත් Program.cs එක තුෂමයි. නෙයිේ දැක්නලේනේ
පංචි Address Book එකක් සාදාගැනීෙට හැකි මූලික
සැකස්ෙකි.
උදාහරණය -4
using System;
class Address
{
public string name;
public string address;
}
class MethodParams
{
public static void Main()
{
string myChoice;
MethodParams mp = new
MethodParams();
do
{
//Show menu and get input from
user
myChoice = mp.getChoice();
//Make a decision based on the
user's choice
mp.makeDecision(myChoice);
//Pause to allow the user to see
the results
Console.Write("nPress Enter key
to continue...");
Console.ReadLine();
Console.WriteLine();
} while (myChoice != "Q" && myChoice
!= "q"); //Keep going until the user wants
to quit
}
//Method to show menu and get user's
choice
string getChoice()
{
string myChoice;
//Print A Menu
Console.WriteLine("My Address
Book");
Console.WriteLine("===============n");
Console.WriteLine("A - Add New
Address");
Console.WriteLine("D - Delete
Address");
Console.WriteLine("M - Modify
Address");
Console.WriteLine("V - View
Addresses");
Console.WriteLine("Q - Quitn");
Console.WriteLine("Your choice
(A,D,M,V,or Q): ");
/002FMethodsMethod to retrieve the
user's choice
myChoice = Console.ReadLine();
return myChoice;
}
//Method to ask user to make a decision
void makeDecision(string myChoice)
{
Address addr = new Address();
switch (myChoice)
{
case "A":
case "a":
addr.name = "Sunil";
addr.address = "Kandy Road,
Kurunegala";
this.addAddress(ref addr);
break;
case "D":
case "d":
addr.name = "Nimal";
this.deleteAddress(addr.name);
break;
case "M":
case "m":
addr.name = "Aruna";
this.modifyAddress(out
addr);
Console.WriteLine("Name is
now {0}.", addr.name);
break;
case "V":
case "v":
this.viewAddresses("Mahinda", "Sunil",
"Nimal", "Ruwan");
break;
case "Q":
case "q":
Console.WriteLine("Bye!");
break;
default:
Console.WriteLine("{0} is
not a valid choice", myChoice);
break;
}
}
//Method to insert an address
void addAddress(ref Address addr)
{
Console.WriteLine("Name: {0},
Address: {1} added.", addr.name,
addr.address);
}
//Method to remove an address
void deleteAddress(string name)
{
Console.WriteLine("You wish to
delete {0}'s address.", name);
}
//Method to change an address
void modifyAddress(out Address addr)
{
addr = new Address();
addr.name = "Sunil";
addr.address = "Kandy Road,
Kurunegala";
}
//Method to show addresses
void viewAddresses(params string[]
names)
{
foreach (string name in names)
{
Console.WriteLine("Name: {0}",
names);
}
}
}
Output of this program>
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
පසුගිය සතිය සමග සම්බන්ධයි......
METHODS තව දුරටත්.........
පසු ගිය ලිපි දෙදෙන්ම අපි METHODS ගැන ෙතා
ෙළා.....උොහරණ 4 ක් අධ නය ෙළා. ෙැන් අපි
METHODS ල඼ ප්ර.ධාන දෙ සස ගැන ඉදගන ගනිමු.
METHODS ප්ර.ධාන දෙ සස දෙෙකින් සමන්විතයි...
sioiteM citatS
METHOD එෙ Static නම් (METHOD එෙස
ෙලින් Static Key Word එෙ ඇත්නම්), ඒලා එම
Class එෙ ඇතුදළමයි පාවිච්චි ෙරන්න දලන්දන්.
ඒ ලදේම ඒලාස පාවිච්චි ෙරන්න පුළුලන් දලන්දන්
එම Class එදක්ම ඇති static variables පමණයි.
[Static Methods can be accessed through the
class; and also they can access only the static
variables within the class.]
Instance Methods
METHOD එක Instance Method එකක් නම් එය
ඳාවිච්චි කළ යුත්තත්, ඒ අදාළ Class එතක් Instance
එකක් හරහායි. (Object එකක් හරහායි.) [Instance
Methods are accessed through an instance of a
class and operates on the instance variables] අපි
කලින් කතා කරපු උදාහරණ තදස යලිත් ඔබ
සැ඼කිල්ත඼න් බැලුතලොත් ඔබට තත්තේවි තමකී
Methods ලේග තදතකන් ලැඩිපුරම අපි භවිතා කතළේ
Objects හරහා access ලන Instance Methods බල.
අද මම මුලින්ම තගන එන උදාහරණය. ඉහත කී
Methods ලේග තදකම මනාල ඔබට තත්රුම කර
තදයි.
using System;
class Program
{
static void MethodA()
{
Console.WriteLine("Static
method");
}
void MethodB()
{
Console.WriteLine("Instance
method");
}
static char MethodC()
{
Console.WriteLine("Static
method");
return 'C';
}
char MethodD()
{
Console.WriteLine("Instance
method");
return 'D';
}
static void Main()
{
// Call the two static methods
on the Program type.
Program.MethodA();
Console.WriteLine(Program.MethodC());
// Create a new Program
instance and call the two instance
methods.
Program programInstance = new
Program();
programInstance.MethodB();
Console.WriteLine(programInstance.Metho
dD());
Console.ReadKey();
}
}
METHOD OVERLOADING
Methods ගැන ලැඩිපුර කතා කරපු අපි දැන් Method
Overloading ගැන කතා කරමු. Method Overloading
ත඼ස හඳුන්ලන්තන් දැනට ඳාවිච්චි තලන Method එකක්
තලනත් parameters තයොදාතගන භාවිතා කිරීමයි.
Method Overloading means reusing a method name,
but with different parameter list....
තම් සංකල්ඳය ද අලතබෝධ කරගැනීමට අපි උදාහරණ
බ඼මු.
class SimpleAdder
{
public static int Plus(int number1,
int number2)
{
return Plus(number1, number2,
0);
}
public static int Plus(int number1,
int number2, int number3)
{
return Plus(number1, number2,
number3, 0);
}
public static int Plus(int number1,
int number2, int number3, int number4)
{
return number1 + number2 +
number3 + number4;
}
}
ඉහත SimpleAdder Class එතක් Plus Method එක තුන්
ලතාලක් ලියවී තිබුනද ඒ එක් එක් අලස්ථාතේදී තයොදාතගන
ඇති parameters ගණන තලනස්ය. තමය අපි Method
Overloading ත඼ස හඳුන්ලනලා. තමම සංකල්ඳය භාවිතා
කිරීම තබොතහෝ තල඼ාලට ඳරිගණකතේ කාේයක්ෂමතාල
ඉහ඼ දැමීමට තහේතු තලනලා. ඊට අමතරල ඔතේ Code එක
ලඩාත් සර඼ කරගන්නට ද හැකි තලනලා.
Method Overloading සංකල්ඳය ප්රාාතයෝකවකල තයොදා ගත
හැකි අලස්ථාලක් දැන් මම ඔබට තඳන්ලන්නම්.
/*This example could be improved by
overloading.*/
using System;
class Program
{
public static void Main()
{
ShowString(string.Empty);
ShowString("Category");
}
static void ShowString(string value)
{
if (value == string.Empty)
{
Console.WriteLine("Popular");
}
else
{
Console.WriteLine(value);
}
}
}
තහො඲යි, ඉහත program එක අඳට Method Overloading
සංකල්ඳය තයොදා තගන ලඩාත් සර඼ සහ කාේයක්ෂම කර
ගත හැකියි. ඳහත ලැඩසටහන බ඼න්න.
using System;
class Program
{
public static void Main()
{
ShowString();
ShowString("Category");
}
static void ShowString()
{
// Send default argument to
overload.
ShowString("Popular");
}
static void ShowString(string value)
{
// We don't need an if check
here, which makes
// ... calling this method
directly faster.
Console.WriteLine(value);
}
}
තහො඲යි, අපි දැන් OOP සංකල්ඳතේ Classes සහ Objects
යන මාතෘකාතේ තබොතහෝ කරුණු කතා කර තිතබනලා.
මීළග ලිපිතයන් අපි OOP සංකල්ඳතේ තලත් ලැදගත්
කරුණු සාකච්ඡා කරමු.
OOP සර඼ල....
3. ENCAPSULATION
මේ මලන මෙක් අපි OOP සංකල්පමේ
ABSTRACTION, CLASSES & OBJECTS
(METHODS ද ඇතුළුල) ගැන ඉො සර඼ල නමුත්
සියලුම අල඾අ කරුු  මඳ ින්  සාක්ඡඡා කාා....අද අපි
OOP සංකල්පමේ ෙලත් ඉොම ලැදගත් පැතිකඩක් ලන,
ENCAPSULATION, එනේ මෙ රතුරු සඟලා ෙැබීම
ගැන, සර඼ල, උදාඳරණ සතිෙල සාක්ඡඡා කරමු.
ENCAPSULATION යන ලචනමේ සර඼ මත්රුම
මෙ රතුරු සඟලා ෙැබීම ය් නයි. (Information
Hiding) OOP සංකල්පමේ දී මමය මය දාග් ම් 
Object Implementation Details සඟලා
ෙබ් නටයි.
ඔබ කල්පනා කරන්නට පුළුලන් ඇයි අපි මේ විදිශට
ම ොරතුරු වඟලන්මන් කිය඼ා. හි න්න, රශවඡ
ම ොරතුරු අඩංගු ආය නයක (බ ංකු, ආරක්඿ක
මෙපාර් මේන්තු ලමේ) කටයතු කරන්නට ඇති මෘදුකාංග
වකවන්න විට ඒ තුෂ භාවි ා ලන සියළුම මේ (Methods,
Varaibles...) වෑම මවේලකයාටම මශෝ අොෂ IT
Department එමක් නි඼ධාරීන් ශ මමෝටම Access
කරන්න ශ කි වුමනොත් එම ම ොරතුරු ල඼ රශවඡ භාලය
වශ ආරක්඿ාල න ති මලනලා.....ඒ නිවා මයි Software
Application Design Time එමක්දී අපට අල඾ඡ පිදදි
අල඾ඡ ම ොරතුරු ව ඟවිය ශ කියි. ල නිෙසුනක්
ග මශොත්, හි න්න ඔබ නිර්මාණය කරන මෘදුකාංගයක,
එය පාවිච්චි කරන මකමනකුට (user) කුමන මශෝ item
list එකක් ඇතුෂත් කරන්නට මබොත් මක් (button)
එකක් අල඾ඡයි කිය඼ා. User ට අල඾ඡ ලන්මන් මබොත් ම
එබීමමන් අොෂ list එක ඇතුල් කිරීමයි. ඔහුට මශෝ ඇයට,
මබොත් ම එබීමමන් list එක ඇතුල් ලන්මන්
මකොමශොමෙ යි ෙ නග නීම අනල඾ඡයි. ඒ නිවා අපි ඒ
ලමේ න් ල඼ මේ ENCAPSULATION සංකල්පය
මයොොගන්නලා.
අපි ෙ න් බ඼මු Program එකක් තුෂ මේ වංකල්පය
මයොො ගන්මන් මකොමශොමෙ කිය඼ා.
Coding ලලින් උදාහරණයක් ගෙන එන්නට කලින්
පහත දැක්ගලන සටහනින් ඔබට මා ගේ කියූ ගේ ඉතා
ගහොඳින් ලටහා ෙත හැකියි.
ඕනෑම පරිෙණක භාෂාලක (High Level Language)
ENCAPSULATION සංකල්පය implement කිරීම
සඳඳා මය දාග් ම්  ඒ භාෂාලට අදාළ පරිහරණ ගයදුේය.
(Access Specifiers)
Types of Access Specifiers in C#:
 public – The members (Functions &
Variables) declared as public can be accessed
from anywhere.
 private – Private members cannot be
accessed from outside the class. This is the
default access specifier for a member, i.e. if
you do not specify an access specifier for a
member (variable or function), it will be
private. Therefore, string PhoneNumber; is
equivalent to private string
PhoneNumber;
 protected – Protected members can be
accessed only from the child classes.
 internal – Internal members can be accessed
from anywhere within the application. This is
the default access specifier for a class.
 protected internal – Similar to protected,
protected internal members can be accessed
from the child classes but only within the
application.
ල ෙගත්: Members඼ට එයා඼මේ Memeber functions
ඕමන මල඼ාලක Acces කරන්න පුළුලනි. (Access
Specifier එක කුමක් වුලත්.)
අපි ගේ ෙැන පසුලටත් තල කතා කරමු......
ගේ නිදසුන බ඼න්න. ඔබ ගමය Type කර Run
කරන්නට උත්සහ කරන්න. එන Errors අඳුනාගෙන
Encapsulations අලගබෝධ කරෙන්න.
class House
{
// Data Members
public string DrawingRoom;
private string Kitchen;
// Member Functions
private bool
EnterDrawingRoom()
{
DrawingRoom = "The
Drawing Room";
}
public bool EnterKitchen()
{
Kitchen = "The
Kitchen"; /* Even though Kitchen
is declared Private, EnterKitchen
function can modify it because
the member function itself has
access to all other members. */
}
}
class MainClass
{
public static void Main()
{
House TheBlackHouse
= new House();
TheBlackHouse.DrawingRoom =
"Main Drawing Room"; /* OK -
Public Data Member is accessible
from outside the class */
TheBlackHouse.Kitchen =
"Main Kitchen"; /* Error -
Private Data Member is not
accessible from outside the class.
*/
TheBlackHouse.EnterDrawingR
oom(); /* Error - Private Member
Function is not accessible from
outside the class. */
TheBlackHouse.EnterKitchen(
); /* OK - Public Data Member is
accessible from outside the class.
*/
}
}
මීළඟ නිදසුන:
Declaring a Method with a public Access Modifier:
BankAccountPublic.cs
using System;
class BankAccountPublic
{
public decimal GetAmount()
{
return 1000.00m;
}
}
The GetAmount() function is public. So, it can be
called by code that is external to this class. Now, you
can write the following code, elsewhere in your
program, to use this function:
BankAccountPublic bankAcctPub =
new BankAccountPublic();
// call a public method/function
decimal amount =
bankAcctPub.GetAmount();
ඔබ සැමට 2012 ලසර ජයග්රාාහී ව ලසරක් ම ලා!!!!!
- ෙරිඳු වීරසිංඳ
මීෂඟ මකොටව ඼බන වතිමේ.........
පරිගණක ඉංජිම් රු, ෙරිඳු වීරසිංඳ විසිනි
OOP සරලව....
ENCAPSULATION තල දුරටත්.....
මේ ලිපිය තුළිනුත් අපි සාකච්ඡා කරන්මන්
ENCAPSULATION සංකල්ඳය තුළ ඇති විවිධ
මයදීේ පිළිබ඲ලයි....ඳසුගිය සතිමේ ඳළවූ ලිපිමේ
ඉදිරිඳත් ක඼ මේ ගැන ඔබට ම ො඲ අලමබෝධයක් ඇතැයි
සිතනලා...එම ලිපිමේ අපි කතා ක඼ මේලල් මතක
තබාමගන මේ ලිපිය ඳරිශී඼නය කරන්න!
පසුගිය ලිපිය අලසන් කලේ public Access Modifier
එක භාවිතා කරන ආකාරය ලපන්ලා ලෙමිනුයි. අෙ අපි
මුලින්ම බ඼මු private Access Modifier එක භාවිතා
කරන ආකාරය...
Declaring a private Field: BankAccountPrivate.cs
using System;
class BankAccountPrivate
{
private string m_name;
public string CustomerName
{
get { return m_name; }
set { m_name = value; }
}
}
අපි ඉහත get සහ set methods ල඼ට getter සහ
setter methods කිය඼ කියනලා.....ඔබට ෙැකගන්නට
පුළුලන් ලකොලහොමෙ අොළ Customer Name එක
m_name කියන field එක තුළ අන්තර්ගත කර ඇති
ආකාරය. ලහොඳින් බ඼න්න, m_name field එක,
CustomerName කියන property එක තුළ සැඟවි඼යි
තිලබන්ලන්. එනම් එය තමයි අප බ඼ාලපොරාත්තු ලලන
ENCAPSULATION එක.
m_name එක private ම඼ස declare කර ඇති නිසා
මේ code එමකන් (BankAccountPrivate class
එමකන්) එළිමේ ඔබට m_name එක access කරන්න
බෑ, ඒ මලනුලට public CustomerName property එක
පාවිච්චි කරන්න පුළුලන්. අපි ලම් විදිලහේ තල නිෙසුනක්
බ඼මු. එවිට තලත් ලමය පැහැදිලි ලේවි ඔබට....
class Person
{
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
}
age එක public variable එකක් විෙහට තිබුනානම්, ඕලන්
ලකලනකුට Main method එක තුළ පහත විදිහට age
එක access කර඼ා අගයන් ලලනස් කරන්න පුළුලන්....
Person p = new Person();
p.age = -10;
එතමකොට මමහි ENCAPSULATION එකක්
නැ ැ....නමුත් දැන් මමහි ENCAPSULATION එකක්
තිමබනලා....ඒ නිසා, age එක access කරන්මන්
මමම මයි:
Person p = new Person();
p. Age = -10;
ඉහත Person Class එක අපට පහත පරිදි ඉතා සර඼
ආකාරයටත් ලියන්න පුළුලනි. (ඉහතින් ලිය තිබ්ලබන්ලන්
C# හි සමහර සම්මත methods (default methods) එනම්,
get, set සහ value ලයොොලගනයි. ඒලා ලයොොලනොලගන
වුලෙ ENCAPSULATION සංකල්ඳය පහත
ආකාරයට ඉදිරිපත් කරන්නට පුළුලනි.
class Person
{
//Default value for the
private variable. If not assigned it
will be 0
private int age;
//Method to Set the Age
public void SetAge(int
ageSet)
{
age = ageSet;
}
//Method to Get the Age
public int GetAge()
{
return age;
}
}
ලැදගත්: parameter එකක් විදි ට එලන variable එමක්
නමත් (උ.දා. ageSet) private variable එමක් නමම
නේ, (මේ නිදසුමන් නේ age) අඳට set method එමක්දී
(මේ නිදසුමන් නේ SetAge() ) value එක assign
කිරීමේදී this key word එක මයොදාගන්න
මලනලා...( උ.දා.this.age = age;)
ඊට අොළ Program Class එක:
class Program
{
static void Main(string[]
args)
{
Person p1 = new
Person();
//Set Age
p1.SetAge(35);
//Get Age
Console.WriteLine("nAge
of the Person = " + p1.GetAge());
Console.ReadKey();
}
}
ඔබට හිලතනලා ඇති ලයසක් 0 ට ලඩා අඩු විය ලනොහැකි
බල. ඒ නිසා 0 ට ලඩා අඩු අගයක් Age හි value එක ල඼ස
කේරුහරි ඇතුේ කල඼ොත් එය ලැරදි බල අපට ලම් setter
method එක තුලින්ම ලේනලා දිය හැකියි....ඊට අපි,
validation එකක් යයි කියමු. ඔබට අල඾. පරිදි ලමලන්
vaidations ලයෝොගාත හැකියි.......Encapsulation තුළින්
඼ැලබන තල ලාසියක් තමයි ඒ. පහත නිෙසුන ලමය ඔබට
මනාලට කියා ලේවි....
class Person
{
//Default value for the
private variable. If not assigned
it will be 0
private int age=1;
public int Age
{
get { return age;}
set {
if(value <0){
Console.WriteLine("nInvalid age!
That age is: " + value);
}else{
this.age =
value;
}
}
}
}
ඊට අොළ Program Class එක:
class Program
{
static void Main(string[]
args)
{
Person p1 = new
Person();
Person p2 = new
Person();
//Set Age
p1.Age = 35;
p2.Age = -20;
//Get Age
Console.WriteLine("nAge of
Person1 = " + p1.Age);
Console.WriteLine("nAge of
Person2 = " + p2.Age);
Console.ReadKey();
}
}
මීළඟ ලකොටස ඼බන සතිලේ.........
පරිගණක ඉංජිනේරු, තරිඳු වීරසංශ විසනි
OOP සරලව....
OOP හි තලත් ලැදගත් අංග කිහිපයක්....
නේ ලිපිය තුළිේ අපි වාකච්ඡා කරේනේ OOP
වංකල්පය තුෂ ඇති, CLASSES වශ OBJECTS
වමග වබැඳි තලත් වින඾ේ඿ නයදීේ කිහිපයක් පිළිබඳලයි....
COHESION & COUPLING
Cohesion:
මෙහිදී අදහස මෙමෙන්මන්, Class එෙක් කුෙක් මහෝ
එක් වස්තුවෙට අදාළ, ගැළමඳන ොර්යයන් ස඲හා
ඳෙණක් define ෙෙ තිබීෙයි. අපි හිතමු
StudentDetails කියලා එෙක් ඔබ ලියනවා
කියලා...එයින් ෙෙන්මන් Student Details Set ෙෙලා
Print ෙෙන එෙ වමේ, Student Details වලට ඳෙණක්
අදාළ වූ මේවල් නම්, ඔබ Cohesion සංෙල්ඳය
අනුගෙනය ෙෙ තිමබනවා. Student Details Class එෙ
තුළ ඔබ මවනත් Class එෙක් තුළ තිබිය යුතු Method
එෙක් ලියා ඇත්නම්, [උදා: printSubjectList( )
වමේ, SubjectDetails වැනි Class එෙෙට අදාළ
Method එෙක්] ඔබ Cohesion සංෙල්ඳය අනුගෙනය
ෙෙ නැහැ. එය, සාර්ථෙ Class Design එෙක් මලස
සැලමෙන්මන් නැහැ.
ඳහත දක්වා ඇති උදාහෙණය මෙය වඩා මහොඳින්
ඳැහැදිලි ෙෙනවා.....
class StudentDetails
{
private String firstname;
private String surname;
private String street;
private String city;
/*Default Constructor*/
public StudentDetails()
{
}
/*Method to set the name*/
public void setName(String
f, String s)
{
firstname = f; surname
= s;
}
/*Method to set the
address*/
public void
setAddress(String st, String c)
{
street = st; city = c;
}
/*Method to print the
name*/
public void printName()
{
Console.WriteLine("Name: ",
firstname, surname);
}
/*Method to print the
address*/
public void printAddress()
{
Console.WriteLine("Street: ",
street);
Console.WriteLine("City:
", city);
}
}
ඉහත StudentDetails Class එෙ Cohesion
සංෙල්ඳය අනුගෙනය ෙෙ තිමබනවා.
Cohesion is the Object Oriented principle which is
making sure that a class is designed with a single,
well focused purpose!
The higher the Cohesion the “better”!
Coupling:
1. Low Coupling: මෙෙගින් අදහස්
මෙමෙන්මන් එෙ Class එෙෙට යම් මවනස්
ෙෙක් ෙළමහොත් ඊට සම්බන්ධ අමනක් Classes
වලට මවනසක් කිරීෙට අවශ්යන මනොීමෙයි.
2. High Coupling: මෙෙගින් අදහස්
මෙමෙන්මන් එෙ Class එෙෙට යම් මවනස්
ෙෙක් ෙළමහොත් ඊට සම්බන්ධ අමනක් Classes
වලට ද මවනසක් කිරීෙට අවශ්යන ීමෙයි.
Low Coupling is better than High Coupling!
අපි Coupling ගැන නත්රුේ ගනිමු පශත උදාශරණනයේ:
Classes නදක මුලින් තිබෙන විදිහ:
class ContactDetails
{
private Phone phone;
private String street;
private String city;
/* Constructor*/
public ContactDetails(Phone p,
String s, String c)
{
phone = p; street = s; city =
c;
}
/*Method to print*/
public void print()
{
Console.WriteLine("Street:
", street);
Console.WriteLine("City: ",
city);
Console.WriteLine("Phone: ",
phone);
}
/*Method to return city*/
public String getCity() { return
city; }
}
class Phone
{
private int area;
private int number;
/*Constructor*/
public Phone(int a, int n,
ContactDetails c)
{
area = a; number = n;
validateArea(area,
c.getCity());
}
}
*Note: validateArea ( ) method එෙ define ෙෙ
නැති අතෙ මෙෙ සංෙල්ඳය ඳැහැදිලි කිරීෙට එහි
අන්තෙගතය මෙහිදී අවශ්යනෙ නැත.
ContactDetails constructor එනක් නලනව
බ඼ේන:
class ContactDetails
{
private Phone phone;
private String street;
private String city;
/* Constructor*/
public ContactDetails(int a, int
n, String s, String c)
{
validateArea(a, c);
phone = new Phone(a, n);
street = s; city = c;
}
.................... /*The other methods are the
same*/
.....................
ඒ අනුල එක නලනව් වුනු ශැටි බ඼ේන:
class Phone
{
private int area;
private int number;
/*Constructor*/
public Phone(int a, int n)
{
area = a; number = n;
}
}
ලැදගත්: නමය නශොඳ Object Oriented Design එකක්
නනනලයි.... මීළඟ මෙොටස ලබන සතියට....
class
ContactDetails
class Phone
OOP වර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංශ විසනි
ASSOCIATION, AGGREGATION,
COMPOSITION
OOP වංකල්පනේදී CLASSES අතර ඇති
වම්බේධතා ගැන අපි අද කතා කරමු.
ASSOCIATION:
නෙෙ වම්බේධතානේදී අදාෂ CLASSES
නදකට අයිති කරුනලක් නැති අතර නදකටෙ
තොටෙ අනේනික ගති ඼ක්඿ණ පලතී.
Association is a (*a*) relationship between
two classes. It allows one object instance to
cause another to perform an action on its
behalf. Association is the more general term
that defines the relationship between two
classes.
(*a*) - *has a* , *use a* basically it is a verb
that we can use!
උදාහරණය:
 StudentRegistrar and RecordManager
classes. (Relationship එක
nssociation
එකඑ ල඼ස අර්ථ දැඑවිය
හැකි අතර ,StudentRegistrar uses a
RecordManager ල඼ස කිල හැකිය).
ලෙල඼ස ඉහත කී ලේ ලඳන්විය හැකිය.
Code එක ගත්ලතොත්:
public class StudentRegistrar
{
public StudentRegistrar ();
{
new
RecordManager().Initialize();
}
}
AGGREGATION
Special type of an association.....
Aggregation is the (*the*) relationship
between two classes. When object of one
class has an (*has*) object of another, if
second is a part of first (containment
relationship) then we called that there is an
aggregation between two classes. Unlike
association, aggregation always insists a
direction.
Aggregation එකක් වින඾ේෂිත වූ Association
එකකි. එය Association එකක් නශොඳිේ විව්තර
කරයි. එයට ශැෙනල඼ානලෙ දි඾ාලක්
තිනබනලා.....
උදාහරණය:
ලේ උදාහරණලේදී, අඳට කියන්න පුළුලන්
University has a Chancellor or University
aggregates Chancellor! කිය඼ා.
Code එක ගත්ලතොත්:
public class University
{
private Chancellor
universityChancellor = new
Chancellor();
}
Note: Chancellor ලකලනඑ නැති උනත්
University එකඑ තිබිය හැකිය. එනිසා තෙයි
nggregation relationship එලඑ හිස ලකොටස
University එක ලදසට තිලෙන්ලන්....ඔෙ Classes
design කරේදී ලේ ලදය ෙතලඑ තො ගත
යුතුයි....එවිට ඔෙට අතර නිලැරදි සේෙන්ධතාලන්
ලගොඩ නැගිය හැකියි...
COMPOSITION
ඉහත උදාහරණයෙ ඉදිරියට ලගනයමින් අපි ලේ
සේෙන්ධතාල ලත්රුෙ ගනිමු.
Chancellor ලකලනඑ නැති උනත් University එකඑ
තිබිය හැකිමුත් University එකඑ නැතුල එහි Faculties
)පීඨ( තිබිය ලනොහැකිය.....ඒ ලලේ අලස්ථාලන් ල඼දී
ලයලදන වම්බේධතා ල඼ට අපි Compositions
යැයි කියනලා...
ලහොඳින් ෙ඼න්න, Class Diagram එලඑ Faculty
Class එක සහ University Class එක අතර
ඇත්ලත් “University has Faculties” යන
සේෙන්ධතාල වුලත් university එකඑ නැති විට
faculty එකඑ ද නැති නිසා එහි ඊ හිස කළු
ලර්ණලයන් යුතුල තිලෙනලා.....
ලහො඲යි, අද අපි සර඼ල අලලෙෝධ කරගත්ලත්,
CLnSSES ලගොඩ නැගීලේදී ලයොදාගැලනන
සේෙන්ධතා ගැනයි....
අපි කතා කරපු ලේලල් සේපිණ්ඩනය කර
ලඳන්වුලලොත් ඳහත සටහනින් එය ෙැනවින්
විදුොන ලලයි.....
මීළඟ ලකොටස ඼ෙන සතිලේ.........
OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
GENERALIZATION
OOP ල඼ Classes ල඼ ප ොදු ඼ක්ෂණ අනුල ඒලා
සැකපසන ආකාරයක් ප඼ස GENERALIZATION
හඳුන්ලමු.
 Entities ල඼ ප ොදු ඼ක්ෂණ හඳුනාගැපන්.
(Attributes පහෝ Behaviours පහෝ ඒ
පෙපක්ම.
 ඒ ප ොදු ඼ක්ෂණ ගසක ආකෘතියක් අනුල
සැකපසේ. (Arranged in a Tree Structure)
 උඩම ඇත්පත් root එකයි. එහි යටපත් ඇති
සියලුම entities ල඼ ප ොදු ඼ක්ෂණ එය තුළ
අඩංගු පලනලා. (ඉහත සටහනට අනුල,
Ellipse සහ Polygon entities ල඼ට Shape
entity එපක් ඼ක්ෂණ ඇති අතර Circle
එකට Shape එපක් ඼ක්ෂණ ල඼ට අමතරල
Ellipse එපක්ෙ ඼ක්ෂණ ඇත.Rectangle
එකට Shape එපක් ඼ක්ෂණ ල඼ට අමතරල
Polygon එපක්ෙ ඼ක්ෂණ ඇත.
 පේ ආකෘතියට Generalization/Inheritance
Hierarchy යැයි කියමු.
INHERITANCE
ප්රEමුඛතම Entity එපක් සිට (Root or Super Class)
හ඼ට ඼ක්ෂණ පප්රEේරණය ම ම පමපසේ හඳුන්ලමු.
Extending Classes
කලිේ අර්ථ දැක්වූ Class ලලිේ අලුත් Classes
නිර්මාණය කිරීම.
In OOP inheritance is a way to form new classes
using classes that have already been defined.
Super Class
ආකෘතිනේ මුලිේම ඇති Class එකයි.
The class from which the subclass is derived is
called a super class (also called as base class or
parent class)
Sub Class
ආකෘතිනේ මුලිේම ඇති Class එක යටනත් ඇත...
A class that is derived from another class is called a
subclass (derived class, extended class, or child class)
INHERITANCE දක්නට ඼ැනෙන ආකාර ල඼ උදාහරණ:
අපි පේ එක එකක් ගැන (Inheritance Types) ඊළඟ
ලිපිපයන් කතා කරමු. අෙ මම Simple Inheritance එකකට
උොහරණයක් පගන එන්නේ: (Sphere class එක Circle
class එක Extend කර ඇති අයුරු බ඼න්න.....)
Source File: Circle.cs
namespace FlatShapes
{
class Circle
{
private double _radius;
public double Radius
{
get { return
(_radius < 0) ? 0.00 : _radius; }
set { _radius
= value; }
}
public double Diameter
{
get { return
Radius * 2; }
}
public double
Circumference
{
get { return
Diameter * 3.14159; }
}
public double Area
{
get { return
Radius * Radius * 3.14159; }
}
}
}
Source File: Sphere.cs
namespace Volumes
{
class Sphere : FlatShapes.Circle
{
new public double Area
{
get { return
4 * Radius * Radius * 3.14159; }
}
public double Volume
{
get { return
4 * 3.14159 * Radius * Radius * Radius /
3; }
}
}
}
Source File: Exercise.cs
using System;
using Volumes;
using FlatShapes;
class Exercise
{
static void Show(Circle round)
{
Console.WriteLine("Circle
Characteristics");
Console.WriteLine("Side:
{0}", round.Radius);
Console.WriteLine("Diameter:
{0}", round.Diameter);
Console.WriteLine("Circumference
: {0}", round.Circumference);
Console.WriteLine("Area:
{0}", round.Area);
}
static void Show(Sphere ball)
{
Console.WriteLine("nSphere
Characteristics");
Console.WriteLine("Side:
{0}", ball.Radius);
Console.WriteLine("Diameter:
{0}", ball.Diameter);
Console.WriteLine("Circumference
: {0}", ball.Circumference);
Console.WriteLine("Area:
{0}", ball.Area);
Console.WriteLine("Volume:
{0}n", ball.Volume);
}
public static int Main()
{
FlatShapes.Circle c =
new FlatShapes.Circle();
Volumes.Sphere s = new
Volumes.Sphere();
c.Radius = 20.25;
Show(c);
s.Radius = 20.25;
Show(s);
return 0;
}
}
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
INHERITANCE තව දුරටත්......
Simple/Single Inheritance:
Note: Super Class එකේ properties Derived Class
එකට ඼ැකෙන නිසා ඒලා අලුකෙන් ලිවිය යුතු නැති
අෙර reuse කළ හැකිය. Class එකේ ෙනි Super
Class එකකින් අභා඾ය ගනී නම්, නැෙකහොත් Derive
වුනි නම්, එය Single Inheritance කලයි.
ක ොදුකේ Inheritance සංකල් ය තුළ, Access
Specifiers කයකෙන ආකාරය හෙ සටහනින්
කහොඳින් ක න්ලයි. ඔෙ එහි ඊෙ඼ දි඾ා කෙස කහොඳින්
ෙ඼ා එය කත්රුම් ගන්න.
Simple Inheritance සඳහා උොහරණයේ:
Super Class එක:
Derived Class එක:
Hierarchical Inheritance
කෙය ඉොෙ ෙහු඼ල භාවිො ලන Inheritance ලර්ගයයි.
සටහන ෙ඼න්න. කෙය Hierarchial Inheritance
සංකල් යය සර඼ල ක න්ලා කෙයි. සුල ෙේලා ඇති C#
Class Diagram එක සහ Coding ෙ඼න්න.
C# Class Diagram එක:
C# Class Code එක:
Super Class:
class sampleShape
{
public virtual int area()
{
Console.WriteLine("Virtual
method area of the base class");
return 0;
}
}
Derived Class1:
class sampleRectangle : sampleShape
{
private int arg1, arg2;
public sampleRectangle(int arg1,
int arg2)
{
this.arg1 = arg1;
this.arg2 = arg2;
}
public override int area()
{
return (arg1 * arg2);
}
}
Derived Class2:
class sampleTriangle : sampleShape
{
private int arg1, arg2;
public sampleTriangle(int arg1,
int arg2)
{
this.arg1 = arg1;
this.arg2 = arg2;
}
public override int area()
{
return ((arg1 / 2) * arg2);
}
}
Test Class:
class testClass
{
static void Main(string[] args)
{
sampleShape obj1 = new
sampleRectangle(10,20);
int result1 = obj1.area();
sampleShape obj2 = new
sampleTriangle(10,20);
int result2 = obj2.area();
Console.WriteLine("Area of
Rectangle:{0} nArea of Triangle:{1}",
result1, result2);
Console.ReadKey();
}
}
OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
INHERITANCE තල දුරටත්......
Identifying a valid Inheritance Hierarchy
OOP සංකල්පයේට අනුල ලැඩසටහේ ලිවීනේදී අප
නිලැරදි Inheritance ආකෘති හඳුනාගේනට අල඾ප
නලනලා...ඒ සඳහා සර඼ රීතියක් තිනෙනලා....එය
හඳුේලේනේ ‘is a’ rule කිය඼යි....
Subclass එකෙන් නිරූපිත object එෙ ‘is a’
සම්බන්ධය කයොදා Superclass එෙ සමග ඈ඲ා බ඼ා,
එම සම්බන්ධය ඳලතී නම් එය නිලැරදි Inheritance
එෙක් ක඼ස හඳුනාගනිමු. ඉහත සටහකන් දැක්කලන
Inheritance යතාර්ථලාදීදැයි බ඼මු:
 Region is a Country  False
 Car is a Vehicle  True
 Mouse is a Computer  False
 Circle is a Shape  True
ඒ අනුල, ඳළකලනි සහ තුන්කලනි Inheritance
යතාර්ථලාදී කනොලන අතර (Invalid) කදලන සහ
හතරලන යතාර්ථලාදී (Valid) කලයි....
Types of Inheritance in C#
ඔබ දැන් දන්නලා ඉහතින් දැක්කලන්කන් Simple
Inheritance ආෙෘතියක් බල. C# තුළ, Simple
Inheritance සහ Hierarchial Inheritance නිර්මාණය
ෙළ හැකිමුත් ඳහතින් සටහනින් දැක්කලන Multiple
Inheritance නිර්මාණය ෙළ කනොහැකිය. එය ෙළ හැකි
ලන්කන් Interfaces භාවිතා ෙරමින්ය....(අපි ඒ ගැන
Interfaces ගැන ඉකගන ගන්නාවිට අලකබෝධ ෙරගනිමු.)
METHOD OVERRIDING
මීට ෙලින්, METHOD OVERLOADING ගැන මම
කියා දුන්නා මතෙ ඇති. (එෙම Class එෙ තුළ එෙම
method name එෙ සහිත නමුත් parameters කලනස් method
ඳැලතීම METHOD OVERLOADING කලයි.)
METHOD OVERRIDING ගැන ෙතා ෙළ හැකිලන්කන්
අපි Inheritance ඉකගන ගත්තායින් ඳසුලයි. ඒ
කමොෙද කිව්කලොත්, Inheritance කනොමැතිල METHOD
OVERRIDING ඳැලතිය කනොහැකි බැවිනි.
Usage of ‘Method Overriding’ is enabling the
sub class to provide a specific implementation of
a method that is already provided by one of its
super class(es)
METHOD OVERRIDING තුළින් ලන්කන්, Super
Class එකක් අර්ථ දක්ලා ඇති (defined) method
එෙක් Sub Class එෙ තුළ එහි ොර්යයන්
සම්පූර්ණකයන්ම කගොඩනැගීමයි. ඒ ස඲හා විවිධ
programming langauges විවිධ syntaxes භාවිතා
ෙරනලා. ඒ අතරින් C# , super class එකක් virtual
නමැති keyword එෙත් sub class එකක් override
keyword එෙත් කයොදාගන්නලා...
ඳහත නිදසුන බ඼න්න:
public class Animal {
public virtual void eat(){
Console.WriteLine("Animal
Eating");
}
}
public class cat : Animal{
public override void eat(){
Console.WriteLine("Cat
Eating");
}
}
Note: Sub class එනක් overidden method
එනක් නමත්, parameters ගණනත් Super class
එනක් virtual method එකට සමාන විය යුතුයි.
METHOD OVERRIDING ල඼ට සර඼
උදාහරණයක් සමගින් අද ඳාඩම අලසන් ෙරමු.
(Square - super class; Cube - sub class)
using System;
class TestMehtodOverriding
{
public class Square
{
public double x;
// Constructor:
public Square(double x)
{
this.x = x;
}
public virtual double
Area()
{
return x*x;
}
}
class Cube: Square
{
// Constructor:
public Cube(double x):
base(x)
{
}
// Calling the Area base
method:
public override double
Area()
{
return
(6*(base.Area()));
}
}
public static void Main()
{
double x = 5.2;
Square s = new
Square(x);
Square c = new Cube(x);
Console.WriteLine("Area
of the Square = {0:F2}",
s.Area());
Console.WriteLine("Area
of the Cube = {0:F2}",
c.Area());
}
}
OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
ABSTRACT CLASSES & METHODS
න ොනලද නේ ABSTRACT CLASSES?
කෙටිකෙන් ම කිවක ොත්, සම්පූර්ණ නැති methods
ඇති, එම methods, derived class තුළදී සම්පූර්ණ
ෙළ යුතු ආොරකේ classes කමනමින් ැඳින්කේ...
ABSTRACT CLASS එකක ඼ක්ෂණ අපි පහත පරිදි
හඳුනාගනිමු:
 Can have one or more incomplete
(abstract) methods
 Cannot be used to instantiate objects
 Normally used as base-classes in
inheritance hierarchies
 Derived classes called concrete classes
must define the missing pieces
 Can have instances from the Derived
classes
Abstract methods එෙෙට වැඩි ගණනක් තිබිෙ
ැකි අතර කමම classes වල Objects ැදිෙ
කනො ැකිෙ. Inheritance Hierarchies වල Base
Class එෙ කලස ක ොක ෝවිට කෙොදා ගැකනන්කන්
කමවන් Abstract Classes ෙ.
න ොනලද නේ ABSTRACT METHODS?
සම්පූර්ණ නැති methods නැත්නම් Abstract Class
එෙෙ abstract key word එකෙන් ඳුන්වා ඇති
methods කමනමින් ැඳින්කේ.
ABSTRACT METHOD එකක ඼ක්ෂණ අපි පහත
පරිදි හඳුනාගනිමු:
 Only the method signature is there.
Abstract method declarations are only
permitted in abstract classes
 Mark with the keyword abstract and a
semicolon at the end
 Implementation is missing
 Does not know how to implement the
method
කම්වාකේ ඇත්කත් method signature එෙ පමණි.
රෙ නැත්නම් මදෙ ඇත්කත් derived class එකක්ෙ.
ABSTRACT CLASSES සහ METHODS ල඼ට
උදාහරණ පිරික්සමු:
public abstract class Shape
{
public abstract void
Paint(Graphics g, Rectangle r);
}
public class Ellipse: Shape
{
public override void
Paint(Graphics g, Rectangle r) {
g.DrawEllipse(r);
}
}
public class Box: Shape
{
public override void
Paint(Graphics g, Rectangle r) {
g.DrawRect(r);
}
}
ප ත ආොරෙ වැරදිෙ....compilation error එෙක්
කේවි:
abstract class AbstractBase
{
public abstract void F();
}
class SubClasss: AbstractBase
{
public override void F() {
base.F();
// Error, base.F is abstract
}
}
An abstract method declaration is permitted to
override a virtual method. This allows an abstract
class to force re-implementation of the method in
derived classes, and makes the original
implementation of the method unavailable. In the
examples:
Abstract method එකක් තල යේ class එකක ඇති
virtual methods override කළ හැකි ලන පරිදි
සකසා ඇත. පහත උදාහරණ බ඼ේන:
using System;
class A
{
public virtual void F() {
Console.WriteLine("A.F");
}
}
abstract class B: A
{
public abstract override void
F();
}
class C: B
{
public override void F() {
Console.WriteLine("C.F");
}
}
public class D
{
public virtual void
DoWork(int i)
{
// Original
implementation.
}
}
public abstract class E : D
{
public abstract override void
DoWork(int i);
}
public class F : E
{
public override void
DoWork(int i)
{
// New implementation.
}
}
Abetract Methods, Classes ස ඒවා සම් න්ධ කේ
ගැන අපි ල න සතිකෙත් වැඩිදුර ෙතා ෙරමු.
OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
ABSTRACT CLASSES & METHODS
(CONT.)
ABSTRACT CLASSES & METHODS නහොඳිේ
නේරුම් ගේනට අපි අද තලේ උදාහරණයක් නදස බ඼මු:
අදාළ CLASS DIAGRAM එක:
CarFactory.cs:
SportsCar.cs:
DRIVER CLASS  Driver.cs:
GENERIC FACTORY CLASS 
GenericFactory.cs
ඉහත දැක්වූ ABSTRACT CLASSES ලලිේ ලැඩක්
ගේන CLASS එක නෙයයි:
නෙෙ උදාහරණය හරහා ෙට අල඾ය වූනේ
ABSTRACT CLASSES නයනදේනේ කුෙන
ආකාරනයේදැයි ලඩාේ පැහැදිලි කිරීෙටයි. නෙහි එන
සෙහර නේලල් ගැන අපි පසුලට කතා කරමු. (උ.දා.
Generics)
Output of this example:
OOP සරලව....
DYNAMIC BINDING
What is Dynamic Binding and static
binding ?
In Dynamic Binding, objects are bound to the
reference object on runtime where as in Static
Binding the compiler is straight away aware of
which object is bound before runtime.
උදාහරණ
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Inheritance
{
using System;
using System.Collections.Generic;
namespace TestingSolutions
{
public class Animal
{
public virtual void eat()
{
Console.WriteLine("
Animal Eating");
}
}
public class Cat : Animal
{
public override void
eat()
{
Console.WriteLine("
Cat Eating");
}
public void eat(String s)
{
Console.WriteLine("
Cat Eating" + s);
}
}
class testDynamicBinding
{
static void Main(string[]
args)
{
//Test-1
Animal a = new
Animal();
a.eat();
//Test-2
Cat c = new Cat();
c.eat();
//Test-3
Animal ac = new Cat();
ac.eat();
//Test-4
Cat c1 = new Cat();
c1.eat(" Meat");
//Test-5 : Gives Errors (Animal class's
eat() method does not take arguements)
Animal a2 = new Animal();
a2.eat(" Meat");
//Test-6 : Gives Errors (Cat object of
Animal type also does not have an eat()
method to take args)
Animal ac1=new Cat();
ac1.eat(" Meat");
//Test-7: Syntactically this is wrong:
Can't convert a lower type reference to
a higher type in the hirachcy
Cat myCat = new Animal();
Console.ReadKey();
}
}
}
}
තවත
DynamicBinding.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class DynamicBinding
{
public virtual void abcd()
{
Console.Write("In base
classn");
}
}
// This is the junior class
class DBInherit : DynamicBinding{
public override void abcd()
{
Console.Write("In junior
classn");
}
public void abcd2()
{
Console.Write("In
junior classn");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class Program
{
static void Main(string[] args)
{
#region This code is used
to show the dynamic binding
DynamicBinding _objDB =
new DynamicBinding();
_objDB.abcd();
DynamicBinding _objDB2 =
new DBInherit(); //This is an example
of Dynamic Binding as the compiler
did'nt know if there is a method
overriding the base class method
_objDB2.abcd();
Console.ReadKey();
#endregion
}
}
}
OUTPUT
OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
Reference Variable Casting
පසුගිය වතියේ අපි කතා කයේ Dynamic Binding
ගැනයි. යේ වතියේදී අපි Reference Variable
Casting ගැන කතා කරමු. ඔබ දන්නලා, OOP හි
ප්රයධානත වකකේපයක් Inheritance ශරශා අපි Super
Class එයක් සිට Junior Class එකට ඼ක්඿ණ යප්රයහරණය
වී අපි ඉයගන ගත්තා... Inheritance ගැන ඉයගන
ගත්තායින් අනතුරුල අපි Method Overriding, Abstract
Methods/Classes වශ Dynamic Binding ඉයගන
ගත්තා. ඒලා සියේ඼ Inheritance ව ග එකට බැඳුණු
යේලේය.....ඉතින්, අදත් අපි Inheritance ව ග වබැඳි
තලත් එලැනි ලැදගත් යදයක් ලන Reference
Variable Casting ගැන ඉයගන ගනිමු.
එක ලර්ගයක Object එකක් තලත් ලර්ගයකට
සමාන කිරීනේදී නමම Casting ක්රරමය නයොදා
ගැනේ. තලත් විදිහකිේ කිව්නලොත්, එක class
එකකට reference එකක් ඇති object එකක්,
තලත් class එකකට reference එකක් ඇති object
එකක් සමග සේබේධ කිරීමට Casting කිරීම
නයොදා ගැනේ!
Casting ලර්ග නදකක් තිනබනලා...
 Up-Casting:
 Assign the SUB class reference to a
SUPER class reference.
 Always SAFE!
 Implicit cast
 Down-Casting:
 Assign the SUPER class reference to a
SUB class reference.
 Always not an safe operation
 Need an explicit cast
Up-casting ල඼දී, අපි SUB class reference
එකක් SUPER class reference එකකට ව ාන
කරනලා, නැත්නේ වේබන්ධ කරනලා...එය
වා ානd යදයක්. එනේ ‘Up-casting’ කිසිඳු
ගැටළුලක් නැතිල පාවිච්චි කරන්නට පුළුලන්.
Down-casting ල඼දී, අපි SUPER class
reference එකක් SUB class reference එකකට
ව ාන කරනලා, නැත්නේ වේබන්ධ කරනලා...එය
නේ එතරේ වා ානd යදයක් යනොයලයි. ඒ
කියන්යන්, ‘Down-casting’ එතරේ ආරක්ෂිඒත
ලන්යන් නැශැ....
නේ නලනස්කේ නත්රුේ ගනිමු අපි පුකචි උදාශරණයක්
තුළින්....
සිතන්න Car වශ Van classes යදක Vehicle super
class එයකන් inherit යලනලා කිය඼ා...ය න්න යේ
විදිශට :
එතනකොට Up-casting කියන්යන් යේ ලයේ
අලව්ථාලකට:
Vehicle එකක්, Car එකක් විය ශැකිය. එනේ,
ඕයන යල඼ාලක ය඼ොකු යදයක් යපොඩි යේකට
වේබන්ධ කෂ ශැකිය. 
Down-casting කියන්යන් යේ ලයේ අලව්ථාලකට,
තුන්යලනි යේලියේ ඇත්යත් Down-casting එකයි:
(ඔබට හියතනලා ඇති යදලන යේලියේ තියයන්යන් Up-casting
එකක් යන්ද කිය඼ා....එයශ හිතුනනේ ඔබ ශරි!)
‘v1’ න ැති Van එකට ‘h’ න ැති Vehicle එක
assign කරන්නට යපර ‘h’ ට තියබන්යන් Vehicle
඼ක්඿ණ වුලත් (‘h’ ට තියබන්යන් Vehicle reference
එකක් වුලත්) ‘v’ න ැති Van object එක එයට
assign කර තියබනලා...එබැවින්, ඔබට ‘v1’ න ැති
Van එකට ‘h’ න ැති Vehicle එක assign
කරන්නට අල඾d නේ, ‘h’ ල Van එකක් කර
assign කෂ ශැකියි...
නමුත් පශත ය඼ව ඔබ Code එක ලිව්යලොත් runtime
exception එකක් එනලා...(Type කර Run කර
බ඼න්න)
Vehicle h = new Vehicle();
Van v1 = (Van) h;
ඊට යශහතුල ත යි super class object එකක් යකලින්
sub class object වේබන්ධ කිරී ට යනොදී . එයවහ
කරන්නට නේ ඊට කලින් h ල Van object එකකට
ව ාන කෂ යුතුයි. (ඉශත උදාශරණයේ යපන්ලා ඇති
පරිදි)
අපි දැන් තලත් උදාශරණයක් යලත අලධානය යයොමු
කරමු. එය ඔබට ය Casting ගැන ලැඩි දුරටත් කියා
යදයි:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Casting
{
class Program
{
class Animal
{
public void Eat()
{
Console.WriteLine("Eating.");
}
public override string
ToString()
{
return "I am an Animal.";
}
}
class Reptile : Animal { }
class Mammal : Animal { }
class ShowCasting
{
static void Main()
{
Mammal myMammal = new
Mammal();
/*This is an implicit
cast: i.e. Up-casting*/
Animal tiger =
myMammal;
/*This is an explicit
cast: i.e. Down-casting*/
Mammal otherMammal =
(Mammal)tiger;
//Test-1
Test(new Reptile());
//Test-2
Test(new Mammal());
//Test-3
Test(new Animal());
// Keep the console window
open in debug mode.
System.Console.WriteLine("Press any key to
exit.");
System.Console.ReadKey();
}
static void Test(Animal a)
{
// Cause
InvalidCastException at run time in Test-2
& 3
// Because Mammal & Animal
is not convertible to Reptile
respectively.
Reptile r = (Reptile)a;
}
}
}
}
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
POLYMORPHISM
අපි, නේ වනනතක්, ලිපි දහඅටක් පුරාවට OOP සේබේධ
වැදගත් සංකල්ප පිළිබඳව කරුණු සාකච්ඡා කළා....
අද ලිපිනෙේ අපි කතා කරේනේ OOP හි තවත් වැදගත්
අංගෙක් වන POLYMORPHISM ගැනයි....
Polymorphism, Inheritance සමග එකට සේබේධව
පවතිනවා... Inheritance නනොමැතිව Polymorphism
පැවතිෙ නනොහැකියි…
Polymorphism is the idea of
allowing the same code to be used
with different types, which allows
us to write more generic and
abstract implementations when we
write computer programs using OOP
concepts.
The phrase "poly" implies "many"
"morph" implies "appearance"
මූලිකව Polymorphism වර්ග 3 ක් තියෙනවා.
1. Polymorphism based on Inheritance
2. Polymorphism based on Interfaces
3. Polymorphism based on Abstract
classes
(Interfaces Abstract classes පවතින්යන්ත්
පැවතුයනොත් පමණයි.....නමුත් ඒවා Inheritance
තුළ ඇති විය ේෂ අවස්ථා නිසා Polymorphism
තුළ යකොටස් යෙකක් යෙස අපි ඉයගන ගනිමු...)
අද ලිපිනෙේ අපි Polymorphism based on
Inheritance ගැන දැනගනිමු.... අපි උදාහරණෙකිේ
නේ ගැන අවනබෝධෙක් ඇති කරගනිමු.
හිතන්න Account කිෙෙ Super Class එකක් තියෙනවා
කිෙෙ...අපි ෙන්නවා බැැංකුවෙ Accounts වර්ග කීපෙක්
තියෙනවා. යේ උොහරණයේදී අපි හිතමු වර්ග යෙකක්
තියෙනවා කිෙෙ.....Savings සහ Current යේ වර්ග
යෙයක් තැන්පතු සහ ආපසු ගැනීයේ ක්රිeොවනන්
එකියනකට යවනස්! ඒ නිසා, implementation එකත්
යවනස් යවනවා...Super Class (Account) එයක් virtual
methods override කර තමන්ට අව c ය Derived
Class එක තුළ implement කරගන්න
යවනවා.....ඇත්යතන්ම අපි යේවා, Method Overriding
ඉයගන ගන්නයකොට සරෙව කතා කළා.....ඉතින් ඒ
සැංකල්පෙ අෙ, Polymorphism based on Inheritance
යෙස අපි හඳුනාගන්නවා....පහත Coding නිෙහයසේ
අධ්යcනෙ කරන්න…
Account.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class Account
{
protected string name;
protected float balance;
//Constructor
public Account ( string name, float
balance )
{
this.name = name;
this.balance = balance ;
}
//Method for deposites
public virtual void deposit ( float
amount )
{
balance += amount;
}
//Method for withdraws
public virtual void withdraw(float
amount)
{
balance -= amount;
}
//Display the summary
public virtual void display( )
{
Console.WriteLine ( "Name:
{0} Balance: {1}", name, balance ) ;
}
}
}
SavingAccount.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class SavingAccount : Account
{
static int accno = 10100 ;
int trans ;
public SavingAccount ( string s,
float b ) : base ( s, b )
{
trans = 0 ;
accno++ ;
}
public override void withdraw (
float amount )
{
if ( trans >= 3 )
{
Console.WriteLine
("Number of transactions exceed 3" ) ;
return ;
}
if ( balance - amount < 100
)
Console.WriteLine (
"Below minimum balance!" ) ;
else
{
base.withdraw (
amount ) ;
trans++ ;
}
}
public override void deposit(float amount)
{
if ( trans >= 3 )
{
Console.WriteLine (
"Number of transactions exceed 3" ) ;
return;
}
base.deposit ( amount ) ;
trans++ ;
}
public override void display()
{
Console.WriteLine ( "Name:
{0} | Account no.: {1} | Balance: {2}",name,
accno, balance ) ;
}
}
}
CurrentAccount.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class CurrentAccount : Account
{
static int accno = 20200 ;
public CurrentAccount ( string s,
float b ) : base ( s, b )
{
accno++ ;
}
public override void withdraw(float
amount)
{
if ( balance - amount < 0 )
Console.WriteLine ( "No
balance in account" ) ;
else
balance -= amount ;
}
public override void display()
{
Console.WriteLine ( "Name:
{0} | Account no.: {1} | Balance: {2}",name,
accno, balance ) ;
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class Program
{
static void Main(string[] args)
{
#region This code is used to show
polymorphism
SavingAccount mySavingsAccount = new
SavingAccount ( "Sunil", 10000.00f ) ;
mySavingsAccount.display();
mySavingsAccount.deposit(25000);
mySavingsAccount.display();
Console.WriteLine("n");
CurrentAccount myCurrentAccount = new
CurrentAccount("Indika", 50000.00f);
myCurrentAccount.display();
myCurrentAccount.withdraw(2500);
myCurrentAccount.display();
Console.ReadKey();
#endregion
}
}
} ලබන සතිනේ තවත් නේ ගැන කතා කරමු....
ඔබ සැමට සාමෙ සතුට පිරි සුභ නව වසරක් නේවා!
OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
POLYMORPHISM(තල දුරටත්)
පසුගිය සතිනේ ඉදිරිපත් කළ program එනේ
output එක:
අද අපි කතා කරන්නන් Interface Based
Polymorphism ගැනයි.
Inheritance තුළින් ලනේම තුළින් ද Polymorphism
සංකල්පය නගොඩ නැගිය හැකිය.....Interfaces ගැන
අපි පසුලට කතා කරමු....දැනට අපි එනසේ නම් ක඼
හැකි Class එකක් තිනෙනලා යයි හිතමු (Interfaces
ගැන මම මීළඟ ලිපි ලලින් කියා නදන්නම්)
Class Diagram:
IPrint Interface:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
public interface IPrint
{
void Print();
}
}
නම් IPrint Interface එක පහත දක්ලා ඇති
InventoryItems සහ Personnel නදනකන්
access කළ හැකිය....
අපි දැන් IPrint interface එක
InventoryItems සහ Personnel classes
තුළ implement කරමු.
InventoryItems.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
public class InventoryItems<list> :
List<list>, IPrint
{
public void Print()
{
foreach (list obj in this)
{
Console.WriteLine("Inventory Item: " +
obj);
}
}
}
}
Personnel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
public class Personnel<list> :
List<list>, IPrint
{
public void Print()
{
foreach (list obj in this)
{
Console.WriteLine("Person: " + obj);
}
}
}
}
නම් classes නදක නයොදානගන අපි Program
class එනක් TestIPrintInterface
method එක ලියමු....
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class Program
{
static void Main(string[] args)
{
TestIPrintInterface();
Console.ReadKey();
}
#region This region is used to
show interface based polymorphism
public static void
TestIPrintInterface()
{
// Create an InventoryItems
object and populate it.
IPrint obj = new
InventoryItems<string>();
((InventoryItems<string>)obj).Add("Pen")
;
((InventoryItems<string>)obj).Add("Book"
);
// Print this object.
CommonPrintMethod(obj);
Console.WriteLine();
// Create a Personnel object
and populate it.
obj = new
Personnel<string>();
((Personnel<string>)obj).Add("Sumana");
((Personnel<string>)obj).Add("Mallika");
// Print this object.
CommonPrintMethod(obj);
}
private static void
CommonPrintMethod(IPrint obj)
{
Console.WriteLine(obj.ToString());
obj.Print();
}
#endregion
}
}
Output:
඼බන සතිනේ තලත් නේ ගැන කතා කරමු....
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
POLYMORPHISM(තව දුරටත්)
පසුගිය සතිනේ අපි කතා කන ේ Interface based
Polymorphism ගැනයි. අද අපි තුේවන
Polymorohism type එක ගැන කතා කරමු...ඒ,
Abstract Classes based Polymorohism
ගැනයි...
ඔබට මතකනම්, අපි Abstract Classes සහ
Methods ගැන කතා කන ේ 15වැනි ලිපිය
හරහායි...එහිදී කතා ක නේවල් යලි මතකයට
ගතයුතු නවනවා...
අපි නම් ගැන නවනදා වනේම උදාහරණයක් නයොදා
නගන නත්රුම් ගනිමු.
පහත Class Diagram එක බලේන:
‘Shape’ Class එක base class එක වී, Circle
සහ Square classes නදක එමගිේ inherit වී
ඇත.
මුලිේම බලමු Abstract Class එකක් නනොමැතිව
සාමාන නයේ අපි code ලියන ආකාරය:
Shape.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AbstractPolymorphism
{
class Shape
{
protected int x;
protected int y;
public Shape() { }
public Shape(int x, int y)
{
this.x = x;
this.y = y;
}
public virtual void Draw()
{
Console.WriteLine("Drawing
a SHAPE at {0},{1}", this.x, this.y);
}
}
}
Square.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AbstractPolymorphism
{
class Square : Shape
{
protected int xSquare;
protected int ySquare;
public Square(int x, int y)
{
xSquare = x;
ySquare = y;
}
public override void Draw()
{
Console.WriteLine("Drawing
a SQUARE at {0},{1}", xSquare,
ySquare);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
Circle.cs:
namespace AbstractPolymorphism
{
class Circle : Shape
{
protected int xCircle;
protected int yCircle;
public Circle(int x, int y)
{
xCircle = x;
yCircle = y;
}
public override void Draw()
{
Console.WriteLine("Drawing
a CIRCLE at {0},{1}", xCircle,
yCircle);
}
}
}
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AbstractPolymorphism
{
class Program
{
static void Main(string[] args)
{
Shape myShape = new
Shape(100, 100);
Circle myCircle = new
Circle(200, 200);
Square mySquare = new
Square(300, 300);
myShape.Draw();
myCircle.Draw();
mySquare.Draw();
Console.ReadKey();
}
}
}
Output:
දැන් Shape class එක abstract කළ ොත් Draw()
method එක ‘abstract class based polymorphism’
යටළත් භාවිතා ක හැකිය. මතක තබා ගන්න, අපට
abstract class එකක instances හදන්නට බැහැ.
එනිසා Program class එක තු code ලියන විදිහ
ළෙනස් ළෙනො...
Abstract class එක:
namespace AbstractPolymorphism
{
abstract class Shape
{
protected int x;
protected int y;
public Shape() { }
public Shape(int x, int y)
{
this.x = x;
this.y = y;
}
public abstract void Draw();
}
}
අපි child classes ළදක ළෙනස් කරන්ළන්
නැහැ...Abstract ළෙස define වී ඇති Draw()
method එක ආකාර ළදකකින් භාවිතා වීමක් ඔබ
දකිනො...(කලින් දැක්ළක් inheritance based
polymorphism ළෙස, දැන් දකින්ළන් abstract class
based polymorphism ළෙසයි.) ළමන්න Program.cs
එක ළෙනස් ෙන අයුරු:
namespace AbstractPolymorphism
{
class Program
{
static void Main(string[] args)
{
Shape[] shapes = new
Shape[2];
shapes[0] = new Square(200,
200);
shapes[1] = new Circle(300,
300);
foreach (Shape shape in
shapes)
shape.Draw();
Console.ReadKey();
}
}
}
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
INTERFACES
අද අපි කතා කරන්නන් Interfaces
ගැනයි....Polymorphism ගැන කතා කරද්දී මම
Interfaces නයොදානගන උදාහරණයක් ඉදිරිපත් කළා
මතක ඇති.....අපි අද Interfaces ගැන සවිස්තරව
කතා කරමු. විවිධ ආකාරනේ classes අතර ඇති
නමොන යම් නහෝ සමානකමක් නිනයෝජනය කරන්නට
Interfaces නයොදාගන්නවා....එනසේ නයොදා ගත්තත් ඒ
classes සම්බන්ධතා නගොඩ නැගීම Interfaces වල
අනිවාර්ය වගකීමක් නනොනවයි....
උදාහරණයක් සිතමු. Car Tyre class එකක් සහ Tennis
Ball class එකක් තිනයනවා කියල සිතන්න....Tyre
එකක් (Car Tyre class object එකක්) සහ Tennis Ball
(Tennis Ball class object එකක්) එකක් යන නදකටම
නපොදු වූ ලක්ෂණයක් තමයි Bouncing feature එක...අපි
හිතමු එය Bouncable කියල හඳුන්වනවා කියල. ඉතින්,
ඉහත කී classes නදක ඒ ලක්ෂණය හරහා සම්බන්ධ කර
ගත යුතු නම් අපිට 'Bouncable' කියල Interface එකක්
ලියන්නට පුළුවන්!
සාමාන නයන් අපි Interfaces ලියන නකොට ඉස්සරහට 'I'
නයොදා ලියනවා, නමොකද එතනකොට පහසුනවන් එය
Interfaces එකක් කියල බලු බැල්මට හඳුනාගන්න නල්සි
නිසා…
උදා.
interface IBounceable
{
void bounce();
void setBouncingFactor(int bf);
}
class TennisBall : IBounceable{
private int bounceFactor;
public void bounce(){
…………………
}
public void setBouncingFactor(int
bf){
…………………
}
}
class CarTyre : IBounceable{
private int bounceFactor;
public void bounce(){
…………………
}
public void setBouncingFactor(int
bf){
…………………
}
}
අපි උදාහරණයක්
නදස බලමු:
IAnimal.cs
using
System;
using
System.Colle
ctions.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
interface IAnimal
{
string Name
{
get;
set;
}
string Describe();
}
}
Dog.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class Dog : IAnimal
{
private string dogName;
//Constructor
public Dog(string dogName)
{
this.dogName = dogName;
}
//Implementation of the method
declared in the Interface IAnimal
public string Describe()
{
return "Hello, I'm a dog
and my name is " + this.dogName;
}
//Getter and Setter methods
implemented here (this is also an
interface member)
public string Name
{
get { return dogName; }
set { dogName = value; }
}
}
}
Cat.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class Cat : IAnimal
{
private string catName;
//Constructor
public Cat(string catName)
{
this.catName = catName;
}
//Implementation of the method
declared in the Interface IAnimal
public string Describe()
{
return "Hello, I'm a cat and
my name is " + this.catName;
}
//Getter and Setter methods
implemented here (this is also an
interface member)
public string Name
{
get { return catName; }
set { catName = value; }
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class Program
{
static void Main(string[] args)
{
List<Dog> dogs = new
List<Dog>();
List<Cat> cats = new
List<Cat>();
//Add dogs
dogs.Add(new
Dog("Burampi"));
dogs.Add(new
Dog("Walgakota"));
//Add cats
dogs.Add(new Dog("Ngawwa"));
dogs.Add(new
Dog("Walgakota"));
foreach (Dog dog in dogs)
Console.WriteLine(dog.Describe());
foreach (Cat cat in cats)
Console.WriteLine(cat.Describe());
Console.ReadKey();
}
}
}
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
INTERFACES (තව දුරටත්)
පසුගිය සතියේ ඉදිරිපත් කළ program එයේ
output එක:
යේ සතියයත් අපි Interfaces ගැනම කතා කරමු....ඒ
ගැන වැඩි යතොරතුරු ඉයගන ගනිමු.
Interfaces භාවිතනේ ඇති වාස:
Interfaces තුළ ඇත්යත් declarations (methods,
events, indexers and/or properties) පමණයි.
Interfaces තුළ declarations පමණේ ඇත්යත් ඒවා
inherited classes මගින් ඒ ඒ class එකට අනුකූල
විදිහට implement කරන නිසායි.... ඉතින්
implementations නැති නේ Interfaces වල ඇති
වැදගත්කම යමොකද්ද ?
නිතර යවනස් වන ලේෂණ ඇති Components
එකට සේබන්ධ කරන්නට යයොදාගන්යන්
Interfaces ....
නිතර යවනස් වන ලේෂණ ඇති Components
එකට සේබන්ධ කරන්නට යයොදාගන්යන්
Interfaces .... එකම interface එක use කරන
components extra programming නැතුව
සේබන්ධ කර ගත හැකියි….
ඒ නකොනහොමද කියා විස්තර කරනවා නම් :
ඉන්යටර්ඵයෙස්, තමන්ව use කරන members ලාට
බල කරනවා, එකම විදිහට use යවන methods හැම
member ටම access කළ හැකි යලස implement
කරන්න කියල! [An interface forces each
component to expose specific public members
which will be used in a similar way.]
අපි තවත් සරල උදාහරණයක් නදස බලමු: (ගිය
සතියේ සහ යේ සතියේ කියපු යද්වල් පහසුයවන්
අවයබෝධ කර ගැනීමට)
Defining an Interface: IMyVidusaraInterface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
interface IMyVidusaraInterface
{
void MethodToImplement();
}
}
Using above Interface: InterfaceImplementer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ForVidusara
{
class InterfaceImplementer
{
static void Main()
{
InterfaceImplementer
iImp = new InterfaceImplementer();
iImp.MethodToImplement();
Console.ReadKey();
}
public void
MethodToImplement()
{
Console.WriteLine("MethodToImplement
() called.");
}
}
}
OutPut:
යේ උදාහරණය ඔබට Interface Inheritance එක
ගැන අවයබෝධයේ ලබා යදවි :
IParentVidusaraInterface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VidusaraInterfaces
{
interface
IParentVidusaraInterface
{
void
ParentInterfaceMethod();
}
}
IParentVidusaraInterface
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VidusaraInterfaces
{
interface IMyVidusaraInterface :
IParentVidusaraInterface
{
void MethodToImplement();
}
}
InterfaceImplementer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace VidusaraInterfaces
{
class InterfaceImplementer :
IMyVidusaraInterface
{
static void Main()
{
InterfaceImplementer
iImp = new InterfaceImplementer();
iImp.MethodToImplement();
iImp.ParentInterfaceMethod();
Console.ReadKey();
}
//Implementing the method of
IMyVidusaraInterface
public void
MethodToImplement()
{
Console.WriteLine("MethodToImplement
() called.n");
}
//Implementing the method of
IParentVidusaraInterface
public void
ParentInterfaceMethod()
{
Console.WriteLine("ParentInterfaceMe
thod() called.n");
}
}
}
OutPut:
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
INTERFACES (තව දුරටත්)
පසුගිය සතියේ අපි කතා කය ේ Interfaces ඔයේ
වැඩසටහනකට යයොදා ගන්යන් යකොයහොමද කියලයි.....
යේ ලිපියයන් ද අපි Interfaces වල ප්රාායයිගික යයමමක්
ගැන අවධානය යයොමු කරමු.
යකොයහොමද අපි C# වල IList නමැති Interface එක(one
of the default interfaces provided by C#) අයේ
වැඩසටහනකට යයොදාගන්යන් කියලා....ඒ සඳහා අපි
List Operations (List නමැති Data Structure එක ගැන
ඔබ දන්නවනේ යමය යේරුේ ගැනීම පහසු යවයි, යකයසේ
යවතේ Data Structures & Algorithms ගැන මම
යවනම ලිපි යප ක්, යේ ලිපි යප අවසන් වූ පසු ඔබ
යවත යගන එන්නේ. Interfaces ගැන තරමක් ප්රායයිගික
අවයබිධයක් ලබාමමටයි මම යේ වැඩසටහන ඔබ යවත
යගන එන්යන්. (යේ වැඩසටහයන් ඉතිරිය ලබන සතියේ
ප යවයි) Note: IList extends, IComparable and
IEnumerable.
using System;
using System.Collections;
namespace VidusaraList
{
class SimpleList : IList
{
private object[] contents = new
object[10];
private int count;
public SimpleList()
{
count = 0;
}
/* Implementing IList Members (Add,
Clear, Contains, IndexOf, Insert and
so on....)*/
public int Add(object value)
{
if (count < contents.Length)
{
contents[count] = value;
count++;
return (count - 1);
}
else
{
return -1;
}
}
public void Clear()
{
count = 0;
}
public bool Contains(object value)
{
bool inList = false;
for (int i = 0; i < Count; i++)
{
if (contents[i] == value)
{
inList = true;
break;
}
}
return inList;
}
public int IndexOf(object value)
{
int itemIndex = -1;
for (int i = 0; i < Count; i++)
{
if (contents[i] == value)
{
itemIndex = i;
break;
}
}
return itemIndex;
}
public void Insert(int index, object
value)
{
if ((count + 1 <=
contents.Length) && (index < Count) &&
(index >= 0))
{
count++;
for (int i = Count - 1; i >
index; i--)
{
contents[i] = contents[i
- 1];
}
contents[index] = value;
}
}
public bool IsFixedSize
{
get
{
return true;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public void Remove(object value)
{
RemoveAt(IndexOf(value));
}
public void RemoveAt(int index)
{
if ((index >= 0) && (index <
Count))
{
for (int i = index; i <
Count - 1; i++)
{
contents[i] = contents[i
+ 1];
}
count--;
}
}
public object this[int index]
{
get
{
return contents[index];
}
set
{
contents[index] = value;
}
}
//Implementing ICollection Members
public void CopyTo(Array array, int
index)
{
int j = index;
for (int i = 0; i < Count; i++)
{
array.SetValue(contents[i],
j);
j++;
}
}
public int Count
{
get
{
return count;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
// Return the current instance since
the underlying store is not
// publicly available.
public object SyncRoot
{
get
{
return this;
}
}
//Implementing IEnumerable Members
public IEnumerator GetEnumerator()
{
// Refer to the IEnumerator
documentation for an example of
// implementing an enumerator.
throw new Exception("The method
or operation is not implemented.");
}
public void PrintContents()
{
Console.WriteLine("List has a
capacity of {0} and currently has {1}
elements.", contents.Length, count);
Console.Write("List contents:");
for (int i = 0; i < Count; i++)
{
Console.Write(" {0}",
contents[i]);
}
Console.WriteLine();
}
}
}
යමයට අදා Program.cs එක ලබන සතියේ ඉදිරිපේ
කරන්නේ. ඉහත class එයකන් කරන්යන් list එකකට
elements, add කිරීම, display, delete කිරීම වැනි මූලික
යේවල්ය. (ඔබ යහොඳින් එය අධsනය කරන්න)
Expected Outcome: (Main program will give this
output – it will be published next week)
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
INTERFACES (තව දුරටත්)
Continuing from last week:
පසුගිය සතියේ ඉදිරිපත් කළ SimpleList
නෝiග්රෑයම් එ ටකට ාළ main නෝiග්රෑයම් එ ටක:
using System;
using System.Text;
namespace VidusaraList
{
class Program
{
static void Main(string[]
args)
{
SimpleList test = new
SimpleList();
// Populate the List
Console.WriteLine("Current
Members of the List:");
Console.WriteLine("-------
---------------------");
test.Add("Tharindu");
test.Add("Kamal");
test.Add("Sunil");
test.Add("Rajendra");
test.Add("Indika");
test.Add("Pavithra");
test.Add("Mahinda");
test.Add("Ranil");
test.PrintContents();
Console.WriteLine();
// Remove elements from
the list
Console.WriteLine("Remove
elements from the List:");
Console.WriteLine("-----
-------------------------");
test.Remove("Ranil");
test.Remove("Tharindu");
test.PrintContents();
Console.WriteLine();
// Add an element to the
end of the list
Console.WriteLine("Add
an element to the end of the
List:");
Console.WriteLine("-----
----------------------------------
");
test.Add("Sarath");
test.PrintContents();
Console.WriteLine();
// Insert an element into
the middle of the list
Console.WriteLine("Insert
an element into the middle of the
List:");
Console.WriteLine("-------
--------------------------------------
");
test.Insert(4,
"Karunamuny");
test.PrintContents();
Console.WriteLine();
// Check for specific
elements in the list
Console.WriteLine("Check
for specific elements in the List:");
Console.WriteLine("--------
--------------------------------");
Console.WriteLine("List
contains "Mahinda": {0}",
test.Contains("Mahinda"));
Console.WriteLine("List
contains "Tharindu": {0}",
test.Contains("Tharindu"));
Console.ReadKey();
}
}
}
Output: (යෙය පසුගිය සතියය ෙෙ ඉදිරිපත් කළා)
ය ොඳයි, ඒ අපි බැලුයේ, IList නෙැති C# සතු in-built
interface එක යයොදායෙන basic list operations
කරන ආකාරයයි......
යේවයේ, INTERFACES වල ප්රාායයිගික වාත
අපට ඉයෙන ෙ ැකියි...
දැන් අපි බලමු INTERFACE එකක් ස
ABSTRACT CLASS එකක් අ ර ඇති යවනස් කෙ
යෙොකද්ද කියල....
යවනස ක ා කරන්න කලින්, ඔබ දන්නා පරිදි, යේ
යදයකහි ඇති සොන කෙ යෙොකද්ද?
නම් එ නළනකේම instances සැදිය න ොහැකි වීම
INTERFACE vs ABSTRACT CLASS
Note:
 INTERFACE එකකින් derive වුනු class
එකක INTERFACE එයක් ඇති සියලුෙ
methods implement කළ යුතුය.
 ABSTRACT CLASS එකකින් derive වුනු class
එකක abstract class එයක් ඇති සියලුෙ abstract
methods override කළයුතු වුව ද ABSTRACT
CLASS එක තුළ abstract යනොවන methods
තිබිය ැකි නිසා (implemented) inheritance
තුළින් ඒ method එක derive වුනු class එකට
ලැයබන බව අපි දනිමු.
උදා රණ යදකක් ෙගින් අපි යේවා යත්රුේ ෙනිමු:
public abstract class PassengerVehicle
{
public void Start()
{
Console.WriteLine("The vehicle
has been started");
}
public abstract void Drive();
public abstract void Park();
public abstract void ChangeGear(int
gear);
public void SwitchOff()
{
Console.WriteLine("The vehicle
has been switched off");
}
}
---------------------------------------------------------------
public class Van: PassengerVehicle
{
public Van()
{
}
public override void Drive()
{
Console.WriteLine("The van is
being driven");
}
public override void Park()
{
Console.WriteLine("The van is
being parked");
}
public override void ChangeGear(int
gear)
{
Console.WriteLine("The van
changed gear changed to " +
gear.ToString());
}
}
public interface IVehicle
{
void Start();
void Drive();
void Park();
}
---------------------------------------------------------------
public class Vehicle : IVehicle
{
public void Start()
{
Console.WriteLine("The vehicle
has been started");
}
public void Drive()
{
Console.WriteLine("The vehicle
is being driven");
}
public void Park()
{
Console.WriteLine("The vehicle
is being parked");
}
}
නම් එ OOP ප ඩම් එ ම ල ව ගැ ඔනේ ාළහස් ාපට කියේ !
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
SEALED CLASSES &
METHODS
අද ලිපියෙන් අපි කතා කරන්යන් Sealed Class
ගැනයි.
ඔබට class එකක් base class එකක් කරන්න අවශ්‍ය
නැත්නම්, එහි ඇති methods override කිරීයම්
අවශ්‍යතාවක් නැති නම් class එකක් seal කළ හැකියි.
 Sealed Class:
 Prevents the class from being sub-
classed, means a sealed class cannot be
a base class
 Violates the whole object oriented
notion of inheritance
Why would we ever use a class as sealed?
If and only if we need an absolute
guarantee that none of the methods in
that class will ever be overridden!
C# වල යබොයහොමෙක් in-built classes sealed
යලසයි පවතින්යන්. යහේතුව ඒවා extend කිරීමට
අවසර නැති නිසා....(E.g. String class)
If the String class is not a sealed class, then the
.Net cannot guarantee how a String object
would work on any given system.
Example Sealed Class:
using System;
sealed class MyClass
{
public int a;
public int b;
}
class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.a = 110;
mC.b = 150;
Console.WriteLine("a = {0}, b
= {1}", mC.a, mC.b);
}
}
Another example:
using System;
class MainClass
{
static void Main(string[] args)
{
MySealedClass sealedCls = new
MySealedClass();
int total = sealedCls.Add(4,
5);
Console.WriteLine("Total = " +
total.ToString());
}
}
// Sealed class
sealed class MySealedClass
{
public int Add(int x, int y)
{
return x + y;
}
}
 Sealed Method:
 Prevents the method from being
overridden in a sub class
If a method declaration includes a sealed
modifier, then that method is a sealed method.
If you use the sealed modifier, then it must also
include the override modifier.
Use of the sealed modifier (use of a sealed class)
prevents a derived class from further overriding
the method in a sub class.
Example for sealed methods:
using System;
class A
{
public virtual void methodA1() {
Console.WriteLine("A.methodA1");
}
public virtual void methodA2() {
Console.WriteLine("A.methodA2");
}
}
class B: A
{
sealed override public void
methodA1 () {
Console.WriteLine("B.methodA1");
}
override public void methodA2() {
Console.WriteLine("B.methodA2");
}
}
class C: B
{
override public void methodA2() {
Console.WriteLine("C.methodA2");
}
}
OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි
Note: පසුගිය සතිනේ පළවුනේ 26 වන ලිපියයි.
මුද්රiණ නෂ යයිනේ යය 24 නලස පළවී තිබුණි.
අෂ අපි කතා කරේනේ Immutable Objects
ගැනයි.
Immutable Objects
 කිසිඳු operation එකකට instance එකක
instance variables වෙනස් කළ
වනොහැකිය.
 Any operation that causes such a
change must instead return a new object
with appropriately adjusted instance
variables
 Instance variables set කළ යුත්වත් object
එකක් මුලින්ම හදපු වෙලවෙදියි.....
 Strings are immutable objects
උ.දා.
Immutable object is an object whose state cannot be
modified after it is created!
වමයින් මා ඔබට සරලෙ වෙන ආ, OOP ලිපි වෙළ
අෙසන් වෙනො.... OOP හි සාරාාංශයක් ෙහත
දැක්වෙනො:
Term Definition
Abstract Data
Type
A user-defined data type, including both
attributes (its state) and methods (its
behaviour). An object oriented language will
include means to define new types (see class)
and create instances of those classes (see
object). It will also provide a number of
primitive types.
Aggregation Objects that are made up of other objects are
known as aggregations. The relationship is
generally of one of two types:
 Composition – the object is composed
of other objects. This form of
aggregation is a form of code reuse.
E.g. A Car is composed of Wheels, a
Chassis and an Engine
 Collection – the object contains other
objects. E.g. a List contains several
Items; A Set several Members.
Attribute A characteristic of an object. Collectively the
attributes of an object describe its state. E.g. a
Car may have attributes of Speed, Direction,
Registration Number and Driver.
Class The definition of objects of the same abstract
data type. In Java class is the keyword used to
define new types.
Dynamic
(Late) Binding
The identification at run time of which version
of a method is being called (see
polymorphism). When the class of an object
cannot be identified at compile time, it is
impossible to use static binding to identify the
correct object method, so dynamic binding must
be used.
Encapsulation The combining together of attributes (data) and
methods (behaviour/processes) into a single
abstract data type with a public interface and a
private implementation. This allows the
implementation to be altered without affecting
the interface.
Inheritance The derivation of one class from another so that
the attributes and methods of one class are part
of the definition of another class. The first class
is often referred to the base or parent class. The
child is often referred to as a derived or sub-
class.
Derived classes are always ‘a kind of’ their
base classes. Derived classes generally add to
the attributes and/or behaviour of the base class.
Inheritance is one form of object-oriented code
reuse.
E.g. Both Motorbikes and Cars are kinds of
MotorVehicles and therefore share some
common attributes and behaviour but may add
their own that are unique to that particular type.
Interface The behaviour that a class exposes to the
outside world; its public face. Also called its
‘contract’. In Java interface is also a keyword
similar to class. However a Java interface
contains no implementation: it simply describes
the behaviour expected of a particular type of
object, it doesn’t so how that behaviour should
be implemented.
Member
Variable
See attribute
Method The implementation of some behaviour of an
object.
Message The invoking of a method of an object. In an
object-oriented application objects send each
other messages (i.e. execute each others
methods) to achieve the desired behaviour.
Object An instance of a class. Objects have state,
identity and behaviour.
Overloading Allowing the same method name to be used for
more than one implementation. The different
versions of the method vary according to their
parameter lists. If this can be determined at
compile time then static binding is used,
otherwise dynamic binding is used to select the
correct method as runtime.
Polymorphism Generally, the ability of different classes of
object to respond to the same message in
different, class-specific ways. Polymorphic
methods are used which have one name but
different implementations for different classes.
E.g. Both the Plane and Car types might be able
to respond to a turnLeft message. While the
behaviour is the same, the means of achieving it
are specific to each type.
Static(Early)
Binding
The identification at compile time of which
version of a polymorphic method is being
called. In order to do this the compiler must
identify the class of an object.
වේ ලුහුඬු කිරීම සඳහා මා අන්තර්ජාලවේ සහය
ලබාෙත්තා.
(Reference:
www.ldodds.com/lectures/intro2java/OOP_Terms.doc
)
OOP ලිපි වෙළ වමවලස අෙසන් කරනො....
අපි වෙනත් ලිපි වෙලකින් යලිත් ලබන සතිවේ සිට
හමුවෙමු:
Ad

More Related Content

What's hot (20)

Data Structures & Algorithms in Sinhala
Data Structures & Algorithms in SinhalaData Structures & Algorithms in Sinhala
Data Structures & Algorithms in Sinhala
Tharindu Weerasinghe
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Java swing
Java swingJava swing
Java swing
Apurbo Datta
 
Php array
Php arrayPhp array
Php array
Nikul Shah
 
C Propgramming.pdf
C Propgramming.pdfC Propgramming.pdf
C Propgramming.pdf
Tharindu Weerasinghe
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
Rohit Jain
 
Installation guide for mysql in windows
Installation guide for mysql in windowsInstallation guide for mysql in windows
Installation guide for mysql in windows
sharavanakumar10
 
Java presentation
Java presentation Java presentation
Java presentation
Md. Taiseen Azam
 
Javascript operators
Javascript operatorsJavascript operators
Javascript operators
Mohit Rana
 
Java
JavaJava
Java
proximotechsoft
 
Laravel ppt
Laravel pptLaravel ppt
Laravel ppt
Mayank Panchal
 
Origins and evolution of HTML and XHTML
Origins and evolution of HTML and XHTMLOrigins and evolution of HTML and XHTML
Origins and evolution of HTML and XHTML
Howpk
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
Introduction of Html/css/js
Introduction of Html/css/jsIntroduction of Html/css/js
Introduction of Html/css/js
Knoldus Inc.
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
Tareq Hasan
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
WebStackAcademy
 
Operators
OperatorsOperators
Operators
Then Murugeshwari
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
Dipta Saha
 
Data Structures & Algorithms in Sinhala
Data Structures & Algorithms in SinhalaData Structures & Algorithms in Sinhala
Data Structures & Algorithms in Sinhala
Tharindu Weerasinghe
 
Installation guide for mysql in windows
Installation guide for mysql in windowsInstallation guide for mysql in windows
Installation guide for mysql in windows
sharavanakumar10
 
Javascript operators
Javascript operatorsJavascript operators
Javascript operators
Mohit Rana
 
Origins and evolution of HTML and XHTML
Origins and evolution of HTML and XHTMLOrigins and evolution of HTML and XHTML
Origins and evolution of HTML and XHTML
Howpk
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
Introduction of Html/css/js
Introduction of Html/css/jsIntroduction of Html/css/js
Introduction of Html/css/js
Knoldus Inc.
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
slire
 
JavaScript - Chapter 5 - Operators
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
WebStackAcademy
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
Laurence Svekis ✔
 
Programming in C Presentation upto FILE
Programming in C Presentation upto FILEProgramming in C Presentation upto FILE
Programming in C Presentation upto FILE
Dipta Saha
 

More from Tharindu Weerasinghe (20)

Professionalism & Industry Expectations from undergraduates
Professionalism & Industry Expectations from undergraduatesProfessionalism & Industry Expectations from undergraduates
Professionalism & Industry Expectations from undergraduates
Tharindu Weerasinghe
 
Importance of Knowing what you need to Know!
Importance of Knowing what you need to Know!Importance of Knowing what you need to Know!
Importance of Knowing what you need to Know!
Tharindu Weerasinghe
 
Basics of Computer Networks in Sinhala
Basics of Computer Networks in SinhalaBasics of Computer Networks in Sinhala
Basics of Computer Networks in Sinhala
Tharindu Weerasinghe
 
Tips For A Better Undergraduate Research
Tips For A Better Undergraduate ResearchTips For A Better Undergraduate Research
Tips For A Better Undergraduate Research
Tharindu Weerasinghe
 
Basics of Block Chain
Basics of Block ChainBasics of Block Chain
Basics of Block Chain
Tharindu Weerasinghe
 
Basics of IoT
Basics of IoTBasics of IoT
Basics of IoT
Tharindu Weerasinghe
 
REST API Basics
REST API BasicsREST API Basics
REST API Basics
Tharindu Weerasinghe
 
Cloud Conputing Basics and some Related Research Topics
Cloud Conputing Basics and some Related Research TopicsCloud Conputing Basics and some Related Research Topics
Cloud Conputing Basics and some Related Research Topics
Tharindu Weerasinghe
 
Basic Concepts and Trends in Emerging Technologies
Basic Concepts and Trends in Emerging TechnologiesBasic Concepts and Trends in Emerging Technologies
Basic Concepts and Trends in Emerging Technologies
Tharindu Weerasinghe
 
Introcution to EJB
Introcution to EJBIntrocution to EJB
Introcution to EJB
Tharindu Weerasinghe
 
Introduction to Enterprise Applications and Tools
Introduction to Enterprise Applications and ToolsIntroduction to Enterprise Applications and Tools
Introduction to Enterprise Applications and Tools
Tharindu Weerasinghe
 
Introduction to Agile Software Development & Python
Introduction to Agile Software Development & PythonIntroduction to Agile Software Development & Python
Introduction to Agile Software Development & Python
Tharindu Weerasinghe
 
Agile Languages for Rapid Prototyping
Agile Languages for Rapid PrototypingAgile Languages for Rapid Prototyping
Agile Languages for Rapid Prototyping
Tharindu Weerasinghe
 
Things to ponder before you start building [cooperate] software
Things to ponder before you start building [cooperate] softwareThings to ponder before you start building [cooperate] software
Things to ponder before you start building [cooperate] software
Tharindu Weerasinghe
 
How to make screens and the internet safe for Children
How to make screens and the internet safe for Children How to make screens and the internet safe for Children
How to make screens and the internet safe for Children
Tharindu Weerasinghe
 
Different Concepts on Databases
Different Concepts on DatabasesDifferent Concepts on Databases
Different Concepts on Databases
Tharindu Weerasinghe
 
A Survey Study on Higher Education Trends among Sri Lankan IT Professionals
A Survey Study on Higher Education Trends among Sri Lankan IT ProfessionalsA Survey Study on Higher Education Trends among Sri Lankan IT Professionals
A Survey Study on Higher Education Trends among Sri Lankan IT Professionals
Tharindu Weerasinghe
 
A Survey Study on Higher Education Trends among Information Technology Prof...
A Survey Study  on  Higher Education Trends among Information Technology Prof...A Survey Study  on  Higher Education Trends among Information Technology Prof...
A Survey Study on Higher Education Trends among Information Technology Prof...
Tharindu Weerasinghe
 
Professionalism and Industry Expectations related to IT industry
Professionalism and Industry Expectations related to IT industry  Professionalism and Industry Expectations related to IT industry
Professionalism and Industry Expectations related to IT industry
Tharindu Weerasinghe
 
Triggers and Stored Procedures
Triggers and Stored ProceduresTriggers and Stored Procedures
Triggers and Stored Procedures
Tharindu Weerasinghe
 
Professionalism & Industry Expectations from undergraduates
Professionalism & Industry Expectations from undergraduatesProfessionalism & Industry Expectations from undergraduates
Professionalism & Industry Expectations from undergraduates
Tharindu Weerasinghe
 
Importance of Knowing what you need to Know!
Importance of Knowing what you need to Know!Importance of Knowing what you need to Know!
Importance of Knowing what you need to Know!
Tharindu Weerasinghe
 
Basics of Computer Networks in Sinhala
Basics of Computer Networks in SinhalaBasics of Computer Networks in Sinhala
Basics of Computer Networks in Sinhala
Tharindu Weerasinghe
 
Tips For A Better Undergraduate Research
Tips For A Better Undergraduate ResearchTips For A Better Undergraduate Research
Tips For A Better Undergraduate Research
Tharindu Weerasinghe
 
Cloud Conputing Basics and some Related Research Topics
Cloud Conputing Basics and some Related Research TopicsCloud Conputing Basics and some Related Research Topics
Cloud Conputing Basics and some Related Research Topics
Tharindu Weerasinghe
 
Basic Concepts and Trends in Emerging Technologies
Basic Concepts and Trends in Emerging TechnologiesBasic Concepts and Trends in Emerging Technologies
Basic Concepts and Trends in Emerging Technologies
Tharindu Weerasinghe
 
Introduction to Enterprise Applications and Tools
Introduction to Enterprise Applications and ToolsIntroduction to Enterprise Applications and Tools
Introduction to Enterprise Applications and Tools
Tharindu Weerasinghe
 
Introduction to Agile Software Development & Python
Introduction to Agile Software Development & PythonIntroduction to Agile Software Development & Python
Introduction to Agile Software Development & Python
Tharindu Weerasinghe
 
Agile Languages for Rapid Prototyping
Agile Languages for Rapid PrototypingAgile Languages for Rapid Prototyping
Agile Languages for Rapid Prototyping
Tharindu Weerasinghe
 
Things to ponder before you start building [cooperate] software
Things to ponder before you start building [cooperate] softwareThings to ponder before you start building [cooperate] software
Things to ponder before you start building [cooperate] software
Tharindu Weerasinghe
 
How to make screens and the internet safe for Children
How to make screens and the internet safe for Children How to make screens and the internet safe for Children
How to make screens and the internet safe for Children
Tharindu Weerasinghe
 
A Survey Study on Higher Education Trends among Sri Lankan IT Professionals
A Survey Study on Higher Education Trends among Sri Lankan IT ProfessionalsA Survey Study on Higher Education Trends among Sri Lankan IT Professionals
A Survey Study on Higher Education Trends among Sri Lankan IT Professionals
Tharindu Weerasinghe
 
A Survey Study on Higher Education Trends among Information Technology Prof...
A Survey Study  on  Higher Education Trends among Information Technology Prof...A Survey Study  on  Higher Education Trends among Information Technology Prof...
A Survey Study on Higher Education Trends among Information Technology Prof...
Tharindu Weerasinghe
 
Professionalism and Industry Expectations related to IT industry
Professionalism and Industry Expectations related to IT industry  Professionalism and Industry Expectations related to IT industry
Professionalism and Industry Expectations related to IT industry
Tharindu Weerasinghe
 
Ad

Object Oriended Programming in Sinhala

  • 1. Object Oriented Programming - මූලික සංකල්ප විදුසරට මා ලියූ ලිපි පපළ [2011 – 2012] පරිගණක වලින් වැ ඩගන්න ඉන්න දුවා පුතා ලා පවනුවනි! තුති: මෙවන් මේ ඔබ මවනුවන් ලියා පළ මෙරුෙට උදව් ෙරපු හැ ෙට! මූලිෙ සිේධා න්ත ො හට යළිත් ෙතක් මෙරුවා වූ සියලුෙ මූලා ශ්‍රයන්ට!
  • 2. OOP සර඼ල.... ඳරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි ඳසුගිය කා඼නේ විදුසර හරහා මම ඔබට C ඳරිගණක භාෂානේ මූලික සද්ධාේත කියා දුේ ලිපි නඳළක් නගන ආ බල ඔබට මතක ඇති. නේ ලිපි නඳලිේ අපි අදහස් කරේනේ මෘදුකාංග ඉංජිනේරු ක්නෂේත්රනේ ලැඩිපුරම භාවිතා ලන Object Oriented Programming (OOP) සංකල්ඳය ගැන සර඼ල කියා දීමයි. ලර්තමානනේ නබොනහෝ සංකීර්ණ ඳරිගණක භාෂා (High Level Languages) නමම OOP සංකල්ඳයට අනුකූ඼ න඼ස සකසා තිනබනලා. (උදා: C++, Java, C#, VB.Net) නේ ලිපි නඳනළහි උදාහරණ දැක්වීම ස඲හා මම නයොදා ගේනේ C# ඳරිගණක භාෂාලයි. Object Oriented Programming සංකල්පය තුළින් කකකෙන්කන් අකේ දෛනික ජීවිතය හෙහා ක ොඩ නැගී ඇති සංකල්පයන් පරි ණක වැඩසටහන් කෙණයට ක න ඒමයි. ඕනම වස්තුවක් Object එකක් කෙස සෙකා වැඩසටහන් සැකසීම කමහි ඇති ම෕ලිකම ෙක්ෂණයයි. කහොඳයි, Object Oriented Programming සංකල්පය තුළ ඇති ප්ර්ධාාන ේෂiණ මම පහත කකාෙයට කපන්වන්නම්. 1. ABSTRACTION ABSTRACTION යනු Design Technique එකකි. Object Oriented Programming සංකල්පය තුළ, වස්තුවක (Entity) සංකීර්ණ භාවය ෙඝු කකොට ෛැක්වීමට කමය කයොෛා ැකන්. තවදුෙටත් එය පැහැදිලි කළකහොත්, වස්තුවක සංකීර්ණ ේෂiණ අත්හැෙ වැඩසටහන් කකොටසට අෛාළ ෙක්ෂණ පමණක් කතෝො ැනීම මින් අෛහස් කකකර්. මම එය ඉංග්රී සියෙකයන් කමකෙස ෛක්වන්නම්. Abstraction is an important technique to simplify a complex situation to an understandalbe situation. How ABSTRACTION used in OOP එක් සංකීර්ණ වස්තුවක් සඳහා අෛාළ වන ABSTRACTIONS කීපයක් තිබිය හැකිය. කමහි මීළඟට ෛකවා ඇති ර෕ප සටහන බෙන්න. Salesman යන යන කුෙකය තුලින් බිහි වී ඇති abstractions කෛකක් කේනවා ඇති. (එකක් Medical Database System එකක භාවිතා කිරීමට සුදුසු අතෙ අකනක Sales Tracking System එකක භාවිතා කිරීමට සුදුසුය.) කමහි ඇති වැෛ ත්ම කරුණ වන්කන් කිසියෙයම් ෙඝු කිරීමකට (A given abstraction) අෛාළව ඔබ කයොෛා න්නා විචෙ(න් සහ ්රිnයාවන් (Attributes and Behaviors) ඔබ විසියෙන් නිර්ණය කිරීමයි. එය ඔබ ඔකේ Program එකට කහෝ Project එකට අෛාළව කයොෛා ත යුතුයි. Salesman යන ප්ර්ධාාන කුෙකයට අෛාළ කපොදු ෙක්ෂණ සහ ්රිnයාවන් තිකබන අතෙ Medical Database System එකට කහෝ Sales Tracking System එකට කහෝ අෛාළ Salesman සඳහා පමණක් අෛාළ ෙක්ෂණ සහ ්රිnයාවන් තිකබනවා. (ඉහත සටහකනන් ෛැක්කවන්කන් එයයි.) ABSTRACTION නිර්ණායකය, Attributes(඼ක්ෂඉණ) Behavoirs(ක්රියයාලේ) යන කරුණු කෛකටම බෙපායි. Attributes Behaviours ැන පහත ෛක්වා ඇති සටහන ඉතා වැෛ ත්. Attributes refer to the properties or characteristics associated with an entity and Behaviors refer to the set of actions that the entity can perform. පහත සටහන ඔබට මා කී කෛය මනාවට පැහැදිලි කෙයි. වැඩසටහන්කෙණකේදී Attributes නිර෕පණය වන්කන් Data න඼සත් Behaviors නිර෕පණය වන්කන් Methods කෙසත්ය. Data වෙට උෛාහෙණ කෙස variables, arrays, complex data structures යනාදිය සැෙකිය හැකි අතෙ Methods උෛාහෙණ කෙස operations, functions, procedures සැෙකිය හැකිය. ලැදගත්: Object Oriented Programming සංකල්පය තුළ ක්රගමානුක෕ෙව සැකසුනු Classes, Objects, Interfaces වැනි අං යන් විවිධා Abstractions නිර෕පණය කෙනවා. 2. CLASSLS ඔබට මතක නම්, මම C පරි ණක භාෂාකේ ම෕ලික සියෙද්ධාාන්ත කියාදුන් ලිපි කපකළේ, Structures නමැති කකෘතියක් කියා දුන්නා; C පරි ණක භාෂාකේ ක, ෛත්ත හා නිර෕පිත-්රිnයාවන් (Data & Methods) එකට කකොට සැකසුනු කකෘතියට සමානම කකෘතියක් තමයි Object Oriented Programming තුළ Classes නිර෕පණය කෙන්කන්. Classes තුළ ක ොනු කෙන්කන් කුමක් කහෝ දී තිකබන Abstraction එකකට අෛාළ ෛත්ත, ්රිnයාවන් සහ ඒ ්රිnයාවන් සැකසී ඇති අයුරුයි. (A class derives the specific structure of a given abstraction, like what data it has, what methods it has and how the methods are implemented.) Class එකකින් එයින් නිර෕පිත සියෙයලුම Entities නිකයෝජනය කෙයි. මම එය තවදුෙටත් පැහැදිලි කකළොත්, Salesman Class එක Medical Database System එකක් සහ Sales Tracking System එකක් යන කෛකක්ම සියෙටින Salesmanව නිකයෝජනය කෙයුතුය. Class is used to represent all the members of a given group/class. 2.1 OBJLCTS ෛැන් ඔබ ෛන්නවා, Class එකකින් එක සමාන Entities කීපයක් නිර෕පණය කෙන බව. (A class defines the structure of entire collection of similar things. e.g: Anyone who is a Salesman) නමුත් ෛැන් ඔබට ප්ර්ශ්්නයක් තිකබන්නට ුළුවවන් කකොකහොමෛ අපි Class එකකින් නිර෕පිත එකම කුෙකයකට අයත් කවනස් ති ේෂiණ සහ හැසියෙරීම් ඇති කද්වල් කවන කෙ න්කන් කියො. ඒ සඳහා තමයි Objects නමැති සංකල්පය හඳුන්වාදී ඇත්කත්. An object defines a specific instance of a class. e.g. A salesman whose name is Nimal and has a commision rate of 10%. Objects වලින් කකකෙන්කන් Class එකකින් නිර෕පිත කපොදු ෙක්ෂණ සහ හැසියෙරීම් ඇති කද්වල් වෙ විකශ්ේෂිත කමොකහොතක් නිර෕පණය කිරීමයි. උෛහෙණයක් කෙස, Sales Tracking System එකක්, ඉන්න නිමල් නමැති, කකොමිෂන් අනුපාතය 10% ක් කෛන salesmanව අපට එක Object එකකින් නිර෕පණය කළ හැකිය. පහත ර෕ප සටහන එය මනාවට කපන්වනවා. මීළඟ කකොටස ෙබන සතිකේ.........
  • 3. OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි ඳසුගිය සතිය සමග සම්බන්ධයි...... CLASSES & OBJECTS with EXAMPLES පසුගිය සතිනේ ලිපිනේ අලසානනේ අපි කතා කනේ Classes සහ Objects ගැනයි. නේ සතිනේ අපි ඒ සංකේප නෙක උොහරණ ඔස්නසේ නේරුේ ගනිමු. උොහරණය -1 අපි ගිය සතියේ කතා ක඼ Salesman Class එක ගැන සිතමු. දී තිබුන දත්ත අනුල එය ඳහත ආකාරයට යගොඩ නැගිය හැකිය. C# ඳරිගණක භාෂාලට අනුලයි මම උදාහරණ යඳන්ලන්යන්. (Coding Syntaxes are according to C#). නෙෙ ලිපි නපළ අලසේ වූ පසු ෙෙ ඔබට පිළිබඳල සර඼ල මූලික අඩිතා඼ෙක් ලැනටන පරිදි ලිපි නපළක් නගන එේනේ. එවිට ඔබට Coding Syntaxes ගැන තලදුරටේ ෙැනගත හැකියි.... using System; class Salesman { //These are attributes private String name; private double commisionRate; private int carsSold; // This is a constructor public Salesman(String name) { this.name = name; } //Methods can be like this public double calcComissionRate() { return (commisionRate * 12); } } උොහරණය -2 අපි තලත් උදාහරණයක් බ඼මු. Planet Class එක යගොඩනගන්යන් යකොයහොමදැයි බ඼මු. එහි Attributes ය඼ස Name, Radius, Gravity යන ඼ක්ෂණ යඳළ ගසා තියබනලා.ඳහත ආකාරයට අපිට C# ල඼ Planet Class එක සැකසිය හැකිය. using System; class Planet { private string name; public int radius; public double gravity; // Constructor wihtout arguements public Planet() { Console.WriteLine("Constructor called!"); } // Constructor wiht arguements public Planet(int r, int g, string n) { radius = r; gravity = g; name = n; } } ඉහත Class එයකහි දැක්යලන ඳරිදි Class එයකහි නමින්ම ඇති Methods ල඼ට අපි Constructors යැයි කියමු. ඒලා යයොදාගන්යන් Class එයකහි Attributes initialize කරගන්නටයි. ඒ ගැන අපි ඳසුල ඉයගන ගනිමු.....(ඉදිරි ලිපි ලලින්) උොහරණය -3 Simple Animal Class එකක් යගොඩ නගමු. එහි විවිධ methods තිබිය හැකිය. අදාළ C# Class එක: using System; class Animal { string type; int size; float speed; int strength; //Constructor public Animal() { Console.WriteLine("Animal constructor"); } //Methods... public void Greet() { Console.WriteLine("Animal says Hello"); } public void Talk() { Console.WriteLine("Animal talk"); } public virtual void Sing() { Console.WriteLine("Animal song"); } }; යහො඲යි දැන් අපි බ඼මු යකොහමද යම් Classes ල඼ instances, එයහමත් නැත්නම් Objects නිර්මාණය කරන්යන් කිය඼ා. අපි ඊට යයොදාගන්යන් new Operator එකයි. (C++, Java & C# all uses this “new” operator to declare and initialize objects of classes.) අපි බ඼මු යකොයහොමද ඉහත නිර්මාණය ක඼ Classes තුයන් Objects හදා ගන්යන් කිය඼ා....ඒ ස඲හා මම යයොදාගන්යන් Main program එකයි. C# ල඼ ප්රගධාන Method එක ඇති Class එක අපි Program Class එක ය඼ස හඳුන්ලනලා. Programs Run කරන්නට අපිට යම් Class එක ඕයන් යලනලා. දැන් ඳහත ඇති Object Delcarations සහ Initialization යහොඳින් බ඼න්න...... using System; namespace TestingClasses { class Program { static void Main(string[] args) { //Objects of Salesman Class Salesman sm1 = new Salesman("Nimal"); Salesman sm2 = new Salesman("Mapa"); //Objects of Planet Class Planet p1 = new Planet(); Planet p2 = new Planet(); //Objects of Animal Class Animal a1 = new Animal(); Animal a2 = new Animal(); Console.ReadKey(); } } } යම් ඳාඩම සර඼ කරන්නට මම එකම Project එයක් යම් Classes සියල්඼ම යයෝදාගත්තට, සැබෑ Programming ල඼දී ඒ Project එකට අදාළ Classes ඳමණයි යයොදාගන්යන්. Salesman, Planet & Animal classes are relevant to different projects. But to demonstrate I have used all of them in one program class. මීළඟ යකොටස ඼බන සතියේ.........
  • 4. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි ඳසුගිය වතිය වමග වම්බන්ධයි...... ‘new’ OPERATOR ඳසුගිය ලිපියේ අලවානයේ අපි කතා කයේ Classes ල඼ Objects ගැනයි. යම් වතියේ මුලින්ම අපි, Classes ල඼ Objects ශදන්නට යයොදා ගත්, new Operator එක කරන කාර්යය යත්රුම් ගනිමු. යමම new operator එක, අලුත් Object (Instance) එක ව඲ශා අල඾w මතකය යලන් කරන අතර අදාෂ Class එයේ නියමිත Constructor එක වම්බන්ධ කරගැනීම ද එයින් ඼බායදන Reference එක Object(Instance) එකට ඼බා දීම ද කරනලා... ‘new’ operator does,  Memory allocation for the new instance  Invoking of the constructor to initialize the new instance  Returning of a reference to the instance CONSTRUCTORS Constructor එකේ යනු, Class එකක Object එකේ එයශමත් නැත්නම් Instance එකේ Initialize කරන්නට යයොදා ගන්නා විය඾ේ඿ Method එකකි. ඔබ විය඾ේ඿යයන්ම මතක තබා ගත යුතු කරණයේ ලන්යන්, යමම Constructors යයොදා යනොයගන ඔබට Class එකක Object එකේ ශදන්නට යනොශැකි බල... Constructors ල඼ ප්රහධාන ඼ේ඿ණ කිහිඳයේ ඳශත දේලන්නම්:  එහි නම Class එයේ නමම විය යුතුය .  එහි Return Type එකේ තිබිය යනොශැකිය.  Default Constructor: o Parameters නැති Constructor එක Default Constructor එක ය඼ව Compiler එක ශඳුනාගනී. o ඔයේ Class එයේ Constructor එකේ යනොමැති නම්, Run Time එයේදී Compiler එක Default Constructor එක නිර්මාණය කරගනී. o Contructors ල඼ට Access Modifiers භාවිතා කෂ ශැකිය. Constructors වලට උදාහරණ-1: public class MySimpleClass { public MySimpleClass() { Console.WriteLine(“Default ”); } } ඉශත දේලා ඇති MySimpleClass() නමැති Constructor එක, Default Constructor එක ය඼ව Compiler එක ශඳුනාගනී. Constructors වලට උදාහරණ-2: public class MySimpleClass { public MySimpleClass(int x) { Console.WriteLine(x); } } ඉශත දේලා ඇති MySimpleClass() නමැති Constructor එකට, එේ Parameter එකේ තියබනලා. එම නිවා අපි එලැනි Constructors ල඼ට Constructor with Parameters යැයි කියනු ඼බනලා. එලන් අලව්ථා ල඼දී, යම් Constructor එක භාවිතා කර Object එකේ Initialize කරනලානම්, අපි Integer Parameter එකේ ද එවිය යුතුයි. නිදර්඾නයකින් යඳන්ලනලානම්: MySimpleClass mySimpleObject = new MySimpleClass(10); ය඼ව අඳට Program Class එනකහි mySimpleObject Object එකේ Initialize කරගත ශැකිය. යම් උදාශරණයේ ආකාරයට Main Program එක Run කෂාම, Console එයකහි (Outputs යඳන්ලන Screen එක) 10 print යලයි... CONSTRUCTOR OVERLOADING එකම Class එයකහි විවිධ Parameters(Arguements) වහිතල Constructors තිබීම යමය඼ව ශඳුන්ලනු ඼ැයේ.එේ එේ Constructor එයකන් කරන කාර්යය යලනව් යේ. ඳශත උදාශරණය බ඼න්න: using System; namespace TestingClasses { class Box { int length; //Attributes of the Box class int width; int height; //Constructor with one parameter public Box(int l) { length = l; width = l; height = l; } //Constructor with three parameters public Box(int h, int w, int l) { length = l; width = w; height = h; } } } Box Class එයකහි Constructors යදකේ overload වී ඇත. ඔබ Box instance එකේ වැදීමට භවිතා කරන Constructor එක අනුල එහි Outcome එක ඼ැයබයි. අපි හිතමු ඔබට ඝනකයේ Initialize කරගත යුතුයි කිය඼ා...එවිට ඳාවිච්චි කෂ යුත්යත් Arguement එකේ ඇති Constructor එකයි. එය ඳශත දැේයලන ය඼ව ක඼ ශැකියි. Box myBox1 = new Box(10); හිතමු ඔබට ඝනකාභයේ Initialize කරගත යුතුයි කිය඼ා...එවිට ඳාවිච්චි කෂ යුත්යත් Arguement තුනේ ඇති Constructor එකයි. එය ඳශත දැේයලන ය඼ව ක඼ ශැකියි. Box myBox2 = new Box(3, 4, 5); CONSTRUCTOR CHAINING එක Constructor එකේ තල Constructor එකේ call කිරීම යමය඼ව ශැඳින්යේ...එය ඳැශැදිලි වීම ව඲ශා ඳශත නිදර්඾නය බ඼මු. using System; namespace TestingClasses { class Box { int length; int width; int height; /*Constructor with three parameters*/ public Box(int h, int w, int l) { length = l; width = w; height = h; Console.WriteLine(l + " " + w + " " + h + "n"); } /*Although this has a constructor chaining this is still a constructor with 1 parameter.*/ public Box(int len) : this(len, len, len) { } } } Program Class එයකහි Instances ශැයදන ආකාරයට Main Program එයකන් ඼බායදන Output එක යලනව් ලන අයුරින් ඔබට ඉශත දී මා කියූ යේ ලැටයශේවි. Box myBox1 = new Box(10); ය඼ව Initialize කෂයශොත් ඼ැයබන Output එක: Box myBox2 = new Box(3, 4, 5); ය඼ව Initialize කෂයශොත් ඼ැයබන Output එක: මීෂඟ යකොටව ඼බන වතියේ.........
  • 5. OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි ඳසුගිය සතිය සමග සම්බන්ධයි...... Static & Non-Static Context තලමත් අඳ සිටින්නන් OOP හි Classes & Objects යන සංකල්ඳනේමයි. නම් ලිපිය තුළ අපි සාකච්ඡා කරන්නන් Static (ස්ථීර) සහ Non-Static (අස්ථීර) විච඼ යන් ගැනයි. C# භාෂානේ ලනේම Java ල඼දීත් ස්ථීර විච඼ යන් හැිනන්ීමම “static” යන key-word එක නයොදා ගැනනනලා. Class එකක static variables නයොදාගැනනන ආකාර අපි උදාහරණ නදකකින් ඉනගන ගනිමු. (උදාහරණ තුළින් අලනබෝධ කර ගැනීම, ම෕඼ධර්ම හරි හැටි ල හාගන්න ඉතාම ලැදගත්.) උදාහරණය-1: Static variable එකක් සහිත ඳහත දක්ලා ඇති Box Class එක අධ නය කරන්න. using System; namespace TestingClasses { class Box { //Non static fields int length; int width; int height; //Static field static int noOfBoxes = 0; //Constructor with three parameters public Box(int h, int w, int l) { length = l; width = w; height = h; Console.WriteLine("nBox constructor with 3 parameters called!n"); Console.WriteLine("Height of the Box = " + h); Console.WriteLine("Width of the Box = " + w); Console.WriteLine("Length of the Box = " + l); noOfBoxes++; Console.WriteLine("No. of Boxes created until now = " + noOfBoxes); } } } දැන් අපි බ඼මු නම් Class එනක් Instances හදා නගන මුලින් ස඲හන් ක඼ Static variable එනකන් ලැඩක් ගන්නන් නකනසේද කියා...ඒ ස඲හා අඳ Program Class එක තුළ ලැඩස හන ලියන්න නලනලා...මීළඟ දක්ලා ඇත්නත් ඒ Class එකයි. (නමම පිටුනේ තීරු ල඼ ඉඩ 100% ක්ම ඳරිහරණය ක඼ යුතු නිසා සමහර Coding Lines අදාළ නේළිනයන් ඉලත්ල ඊළඟ නේළිය නගොස් ඇත...(Microsoft Visual Studio – C# ල඼ ඔබ නම් උදාහරණ type කර බ඼න්න) using System; namespace TestingClasses { class Program { static void Main(string[] args) { Box myBox1 = new Box(10, 10, 20); Box myBox2 = new Box(3, 4, 5); Box myBox3 = new Box(12, 12, 12); Console.ReadKey(); } } } Box Constructor එක call නලන හැම අලස්ථාලකම අනේ static variable එක (noOfBoxes) එකකින් ලැඩි නලනලා. (නමය සිදුලන්නන් Box Constructor එක ඇතුනල් noOfBoxes හි ඒ නමොනහොනත් අගය, එකකින් ලැඩි කරන නිසයි. noOfBoxes++ න඼ස දක්ලා ඇත්නත් එයයි.) ඉහත ලැඩස හනන් Output එක ඳහත ඳරිදි ඔබ දිස්නේවි: ඔබ නඳනනනලා ඇති Box Constructor එක call නලන ලාරයක් ඳාසාම noOfBoxes variable එක එකකින් ලැඩිීම, එනතක් create ීම ඇති Box Objects ගණන නඳන්ලන බල. නම් නේ නමන඼ස ක඼ හැක්නක්, noOfBoxes variable එක static වුනු නිසයි. අපි දැන් static variable එක non-static කර බ඼මු. නලනත් විදිහකින් කිේනලොත්, noOfBoxes variable එක අනනක් non-static variables ලනේම හසුරලනලා. අපි ඒලා Instance variables න඼සද හඳුන්ලනලා. මක්නිසාද, ඒලා (non-static) එක Instance එකක ඳමණක් නයොදා ගැනනන නිසා. ඳහත උදාහරණය තුළින් ඔබ Static & Non-Static සංකල්ඳය නහොිනන් ල හා ගත හැකිය. උදාහරණය-2: using System; namespace TestingClasses { class Box { //Non static(Instance) Variables int length; int width; int height; int noOfBoxes = 0; //Constructor with three parameters public Box(int h, int w, int l) { length = l; width = w; height = h; Console.WriteLine("nBox constructor with 3 parameters called!n"); Console.WriteLine("Height of the Box = " + h); Console.WriteLine("Width of the Box = " + w); Console.WriteLine("Length of the Box = " + l); noOfBoxes++; Console.WriteLine("No. of Boxes created until now = " + noOfBoxes); } } } කලින් නයොදාගැනුණු Program Class එකම නමහිදීත් නයොදාගන්න පුළුලනි. එවි ඼ැනබන Output එක ඳහත ඳරිදි ඔබ දිස්නේවි: නෙහිදී, noOfBoxes variable එක static න ොවුණු නිසා, පළනලනි Box Object එක හැදුනු පසුල noOfBoxes හි අගය එකකිේ ලැඩි වු ත් ඉේ අ තුරුල එහි ලැඩි වීෙක් නපේලේනේ ැහැ. නකොතරම් Box Objects හැදුනත්(නකොතරම් Box Constructor එක call වුනත්) noOfBoxes හි අගය ඳළනලනි Constructor call එනකන් ඳසු එන අගයමයි නඳන්ලන්නන්. නහො඲යි, නම් ලිපිනයන් ඔබ Static & Non- Static Context එක ගැන අලනබෝධයක් ඼බාගන්න ඇතැයි සිතනලා. මීළඟ නකො ස ඼බන සතිනේ.........
  • 6. OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි METHODS තලමත් අප රැදී ඉන්නන් OOP හි Classes & Objects යන වංකල්පනේමයි. නේ ලිපියන් අපි වාකච්ඡා කරන්නන් Classes ල඼ භාවිතා ලන METHODS ගැනයි. Classes තුෂ ඊට අදාෂ ක්රිනයාලන් ඉටු කරගැනීමට අපි METHODS නයොදා ගනිමු. METHOD Declaration syntax: (නපොදුනේ method එකක් අර්ථ දක්ලන ආකාරය) [Visibility] ReturnType MethodName([parameters]) උදාහරණ:  public int CalculateTotal(int x, int y)  public double GetVolume()  public void Celcius_to_Farenheight(); Note: Constructor එකක් යනු වින඾ේ඿ method එකක් බල දැන් ඔබට අලනබෝධ නලනලා ඇති. අපි අද ලිපිනයන් method ල඼ට සර඼ උදාශරණ කිහිපයක් බ඼මු: උදාහරණය -1 Calculator.cs: using System; using System.Collections.Generic; using System.Text; namespace TestingMethods { class Calculator { double sum, diff, mul = 0; float div = 0; /*Default Constructor*/ public Calculator() { } /*This method calculates & prints the sum of the two input varialbes*/ public void CalculateSum(int a, int b) { sum = a + b; Console.WriteLine("n* Sum of the two variables: " + sum); } /*This method calculates & prints the difference between the two input varialbes*/ public void CalculateDiff(int a, int b) { diff = a - b; Console.WriteLine("n* Difference of the two variables: " + diff); } /*This method calculates & prints the multiplication of the two input varialbes*/ public void CalculateMul(int a, int b) { mul = a * b; Console.WriteLine("n* Multiplication of the two variables: " + mul); } /*This method calculates & prints the division between the two input varialbes*/ public void CalculateDiv(int a, int b) { div = a / b; Console.WriteLine("n* Division of the two variables: " + div); } } } Program.cs: using System; namespace TestingMethods { class Program { static void Main(string[] args) { int x = 20, y = 10; Calculator myCalc = new Calculator(); //Find the Addion myCalc.CalculateSum(x, y); //Find the Difference myCalc.CalculateDiff(x, y); //Find the Multiplication myCalc.CalculateMul(x, y); //Find the Division myCalc.CalculateDiv(x, y); Console.ReadKey(); } } } Output of this program: උදාහරණය -2 Sphere.cs: using System; using System.Collections.Generic; using System.Text; namespace TestingMethods { class Sphere { public Sphere() { } public double ReturnArea(double radius) { return (radius * radius * 3.14285714); } public double ReturnVolume(double radius) { return (4 * 3.14159 * radius * radius * radius / 3); } } } Program.cs: using System; namespace TestingMethods { class Program { static void Main(string[] args) { Sphere mySpehre = new Sphere(); Console.WriteLine("nInput the radius of your sphere: "); double rad = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("nYour Sphere Characteristics"); Console.WriteLine("--------- ------------------n"); Console.WriteLine("Radius : {0}", rad); Console.WriteLine("Area : {0}", mySpehre.ReturnArea(rad)); Console.WriteLine("Volume : {0}", mySpehre.ReturnVolume(rad)); Console.ReadKey(); } } }
  • 7. Output of this program:
  • 8. OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි ඳසුගිය වතිය වමග වම්බන්ධයි...... METHODS තල දුරටත්......... මම් ලිපියන් අපි වළකච්ඡළ කරන්මන් ඳසු ගිය වතිමේ ලමේම Classes ල඼ භළවිතළ ලන METHODS ගෆනයි. අදත් අපි METHODS ල඼ට උදළශරණ කිහිඳයක් බ඼මු. ඔබ මම් උදළශරණ Visual C# භළවිතළ කර Type කර Run කර බ඼න්න. මම් වතිමයත් මම උදළශරණ මගන එන්මන් ඔබට මම් වංකල්ඳ (විම඾ේ඿මයන් මම් ලිපි මඳෂ ශරශළ අලුමතන්ම Object Oriented Programming ඉමගන ගන්නළ අයට) වර඼ල වශ මශොඳින් අලමබෝධ වීම ව඲ශළයි. ඔබට මළ කලින් ව඲ශන් ක඼ ඳරිදි, METHODS ලලින් කරන්මන්, ඳරිගණක ලෆඩවටශකින් බ඼ළමඳොමරොත්තු ලන ක්රිනයළලන් ඉ කිරීමයි. ඒ ව඲ශළ ඔබ නිලෆරදිල අදළෂ METHODS, අදාළ CLASS එමක් ලිවිය යුතුයි. අපි අද මුලින්ම මවල්සියවහ උ඿හණත්ලයක් සෆරන්ශයිට් ල඼ට ශරලන වර඼ METHOD එකක් බ඼මු. මමය ලියළ ඇත්මත් Program.cs නෆතමශොත් Main Program එක ඇති ප්ර ධළන Class එක තුෂමය. උදාහරණය -3 using System; class Program { static void Main() { Console.WriteLine("This program converts Celsius To Fahrenheit"); Console.WriteLine("---------------- ---------------------------n"); Console.WriteLine("{0} ==> {1}", 100, ConvertTemp.ConvertCelsiusToFahrenheit(100) ); Console.WriteLine("{0} ==> {1}", 212, ConvertTemp.ConvertFahrenheitToCelsius(212) ); Console.WriteLine("{0} ==> {1}", 50, ConvertTemp.ConvertCelsiusToFahrenheit(50)) ; Console.WriteLine("{0} ==> {1}", 122,ConvertTemp.ConvertFahrenheitToCelsius( 122)); Console.ReadKey(); } static class ConvertTemp { public static double ConvertCelsiusToFahrenheit(double c) { return ((9.0 / 5.0) * c) + 32; } public static double ConvertFahrenheitToCelsius(double f) { return (5.0 / 9.0) * (f - 32); } } } මීෂඟ උදළශරණය මළ මගන එන්මන් විවිධ Parameters භළවිතළ කර Methods ලියන ආකළරය මඳන්ලන්නටයි. මමහි එක MethodParams class එක තුෂ ඇති අතර Address වශ MethodParams යන classes මදකම ඇත්මත් Program.cs එක තුෂමයි. නෙයිේ දැක්නලේනේ පංචි Address Book එකක් සාදාගැනීෙට හැකි මූලික සැකස්ෙකි. උදාහරණය -4 using System; class Address { public string name; public string address; } class MethodParams { public static void Main() { string myChoice; MethodParams mp = new MethodParams(); do { //Show menu and get input from user myChoice = mp.getChoice(); //Make a decision based on the user's choice mp.makeDecision(myChoice); //Pause to allow the user to see the results Console.Write("nPress Enter key to continue..."); Console.ReadLine(); Console.WriteLine(); } while (myChoice != "Q" && myChoice != "q"); //Keep going until the user wants to quit } //Method to show menu and get user's choice string getChoice() { string myChoice; //Print A Menu Console.WriteLine("My Address Book"); Console.WriteLine("===============n"); Console.WriteLine("A - Add New Address"); Console.WriteLine("D - Delete Address"); Console.WriteLine("M - Modify Address"); Console.WriteLine("V - View Addresses"); Console.WriteLine("Q - Quitn"); Console.WriteLine("Your choice (A,D,M,V,or Q): "); /002FMethodsMethod to retrieve the user's choice myChoice = Console.ReadLine(); return myChoice; } //Method to ask user to make a decision void makeDecision(string myChoice) { Address addr = new Address(); switch (myChoice) { case "A": case "a": addr.name = "Sunil"; addr.address = "Kandy Road, Kurunegala"; this.addAddress(ref addr); break; case "D": case "d": addr.name = "Nimal"; this.deleteAddress(addr.name); break; case "M": case "m": addr.name = "Aruna"; this.modifyAddress(out addr); Console.WriteLine("Name is now {0}.", addr.name); break; case "V": case "v": this.viewAddresses("Mahinda", "Sunil", "Nimal", "Ruwan"); break; case "Q": case "q": Console.WriteLine("Bye!"); break; default: Console.WriteLine("{0} is not a valid choice", myChoice); break; } } //Method to insert an address void addAddress(ref Address addr) { Console.WriteLine("Name: {0}, Address: {1} added.", addr.name, addr.address); } //Method to remove an address void deleteAddress(string name) { Console.WriteLine("You wish to delete {0}'s address.", name); } //Method to change an address void modifyAddress(out Address addr) { addr = new Address(); addr.name = "Sunil"; addr.address = "Kandy Road, Kurunegala"; } //Method to show addresses void viewAddresses(params string[] names) { foreach (string name in names) { Console.WriteLine("Name: {0}", names); } } } Output of this program>
  • 9. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි පසුගිය සතිය සමග සම්බන්ධයි...... METHODS තව දුරටත්......... පසු ගිය ලිපි දෙදෙන්ම අපි METHODS ගැන ෙතා ෙළා.....උොහරණ 4 ක් අධ නය ෙළා. ෙැන් අපි METHODS ල඼ ප්ර.ධාන දෙ සස ගැන ඉදගන ගනිමු. METHODS ප්ර.ධාන දෙ සස දෙෙකින් සමන්විතයි... sioiteM citatS METHOD එෙ Static නම් (METHOD එෙස ෙලින් Static Key Word එෙ ඇත්නම්), ඒලා එම Class එෙ ඇතුදළමයි පාවිච්චි ෙරන්න දලන්දන්. ඒ ලදේම ඒලාස පාවිච්චි ෙරන්න පුළුලන් දලන්දන් එම Class එදක්ම ඇති static variables පමණයි. [Static Methods can be accessed through the class; and also they can access only the static variables within the class.] Instance Methods METHOD එක Instance Method එකක් නම් එය ඳාවිච්චි කළ යුත්තත්, ඒ අදාළ Class එතක් Instance එකක් හරහායි. (Object එකක් හරහායි.) [Instance Methods are accessed through an instance of a class and operates on the instance variables] අපි කලින් කතා කරපු උදාහරණ තදස යලිත් ඔබ සැ඼කිල්ත඼න් බැලුතලොත් ඔබට තත්තේවි තමකී Methods ලේග තදතකන් ලැඩිපුරම අපි භවිතා කතළේ Objects හරහා access ලන Instance Methods බල. අද මම මුලින්ම තගන එන උදාහරණය. ඉහත කී Methods ලේග තදකම මනාල ඔබට තත්රුම කර තදයි. using System; class Program { static void MethodA() { Console.WriteLine("Static method"); } void MethodB() { Console.WriteLine("Instance method"); } static char MethodC() { Console.WriteLine("Static method"); return 'C'; } char MethodD() { Console.WriteLine("Instance method"); return 'D'; } static void Main() { // Call the two static methods on the Program type. Program.MethodA(); Console.WriteLine(Program.MethodC()); // Create a new Program instance and call the two instance methods. Program programInstance = new Program(); programInstance.MethodB(); Console.WriteLine(programInstance.Metho dD()); Console.ReadKey(); } } METHOD OVERLOADING Methods ගැන ලැඩිපුර කතා කරපු අපි දැන් Method Overloading ගැන කතා කරමු. Method Overloading ත඼ස හඳුන්ලන්තන් දැනට ඳාවිච්චි තලන Method එකක් තලනත් parameters තයොදාතගන භාවිතා කිරීමයි. Method Overloading means reusing a method name, but with different parameter list.... තම් සංකල්ඳය ද අලතබෝධ කරගැනීමට අපි උදාහරණ බ඼මු. class SimpleAdder { public static int Plus(int number1, int number2) { return Plus(number1, number2, 0); } public static int Plus(int number1, int number2, int number3) { return Plus(number1, number2, number3, 0); } public static int Plus(int number1, int number2, int number3, int number4) { return number1 + number2 + number3 + number4; } } ඉහත SimpleAdder Class එතක් Plus Method එක තුන් ලතාලක් ලියවී තිබුනද ඒ එක් එක් අලස්ථාතේදී තයොදාතගන ඇති parameters ගණන තලනස්ය. තමය අපි Method Overloading ත඼ස හඳුන්ලනලා. තමම සංකල්ඳය භාවිතා කිරීම තබොතහෝ තල඼ාලට ඳරිගණකතේ කාේයක්ෂමතාල ඉහ඼ දැමීමට තහේතු තලනලා. ඊට අමතරල ඔතේ Code එක ලඩාත් සර඼ කරගන්නට ද හැකි තලනලා. Method Overloading සංකල්ඳය ප්රාාතයෝකවකල තයොදා ගත හැකි අලස්ථාලක් දැන් මම ඔබට තඳන්ලන්නම්. /*This example could be improved by overloading.*/ using System; class Program { public static void Main() { ShowString(string.Empty); ShowString("Category"); } static void ShowString(string value) { if (value == string.Empty) { Console.WriteLine("Popular"); } else { Console.WriteLine(value); } } } තහො඲යි, ඉහත program එක අඳට Method Overloading සංකල්ඳය තයොදා තගන ලඩාත් සර඼ සහ කාේයක්ෂම කර ගත හැකියි. ඳහත ලැඩසටහන බ඼න්න. using System; class Program { public static void Main() { ShowString(); ShowString("Category"); } static void ShowString() { // Send default argument to overload. ShowString("Popular"); } static void ShowString(string value) { // We don't need an if check here, which makes // ... calling this method directly faster. Console.WriteLine(value); } } තහො඲යි, අපි දැන් OOP සංකල්ඳතේ Classes සහ Objects යන මාතෘකාතේ තබොතහෝ කරුණු කතා කර තිතබනලා. මීළග ලිපිතයන් අපි OOP සංකල්ඳතේ තලත් ලැදගත් කරුණු සාකච්ඡා කරමු.
  • 10. OOP සර඼ල.... 3. ENCAPSULATION මේ මලන මෙක් අපි OOP සංකල්පමේ ABSTRACTION, CLASSES & OBJECTS (METHODS ද ඇතුළුල) ගැන ඉො සර඼ල නමුත් සියලුම අල඾අ කරුු මඳ ින් සාක්ඡඡා කාා....අද අපි OOP සංකල්පමේ ෙලත් ඉොම ලැදගත් පැතිකඩක් ලන, ENCAPSULATION, එනේ මෙ රතුරු සඟලා ෙැබීම ගැන, සර඼ල, උදාඳරණ සතිෙල සාක්ඡඡා කරමු. ENCAPSULATION යන ලචනමේ සර඼ මත්රුම මෙ රතුරු සඟලා ෙැබීම ය් නයි. (Information Hiding) OOP සංකල්පමේ දී මමය මය දාග් ම් Object Implementation Details සඟලා ෙබ් නටයි. ඔබ කල්පනා කරන්නට පුළුලන් ඇයි අපි මේ විදිශට ම ොරතුරු වඟලන්මන් කිය඼ා. හි න්න, රශවඡ ම ොරතුරු අඩංගු ආය නයක (බ ංකු, ආරක්඿ක මෙපාර් මේන්තු ලමේ) කටයතු කරන්නට ඇති මෘදුකාංග වකවන්න විට ඒ තුෂ භාවි ා ලන සියළුම මේ (Methods, Varaibles...) වෑම මවේලකයාටම මශෝ අොෂ IT Department එමක් නි඼ධාරීන් ශ මමෝටම Access කරන්න ශ කි වුමනොත් එම ම ොරතුරු ල඼ රශවඡ භාලය වශ ආරක්඿ාල න ති මලනලා.....ඒ නිවා මයි Software Application Design Time එමක්දී අපට අල඾ඡ පිදදි අල඾ඡ ම ොරතුරු ව ඟවිය ශ කියි. ල නිෙසුනක් ග මශොත්, හි න්න ඔබ නිර්මාණය කරන මෘදුකාංගයක, එය පාවිච්චි කරන මකමනකුට (user) කුමන මශෝ item list එකක් ඇතුෂත් කරන්නට මබොත් මක් (button) එකක් අල඾ඡයි කිය඼ා. User ට අල඾ඡ ලන්මන් මබොත් ම එබීමමන් අොෂ list එක ඇතුල් කිරීමයි. ඔහුට මශෝ ඇයට, මබොත් ම එබීමමන් list එක ඇතුල් ලන්මන් මකොමශොමෙ යි ෙ නග නීම අනල඾ඡයි. ඒ නිවා අපි ඒ ලමේ න් ල඼ මේ ENCAPSULATION සංකල්පය මයොොගන්නලා. අපි ෙ න් බ඼මු Program එකක් තුෂ මේ වංකල්පය මයොො ගන්මන් මකොමශොමෙ කිය඼ා. Coding ලලින් උදාහරණයක් ගෙන එන්නට කලින් පහත දැක්ගලන සටහනින් ඔබට මා ගේ කියූ ගේ ඉතා ගහොඳින් ලටහා ෙත හැකියි. ඕනෑම පරිෙණක භාෂාලක (High Level Language) ENCAPSULATION සංකල්පය implement කිරීම සඳඳා මය දාග් ම් ඒ භාෂාලට අදාළ පරිහරණ ගයදුේය. (Access Specifiers) Types of Access Specifiers in C#:  public – The members (Functions & Variables) declared as public can be accessed from anywhere.  private – Private members cannot be accessed from outside the class. This is the default access specifier for a member, i.e. if you do not specify an access specifier for a member (variable or function), it will be private. Therefore, string PhoneNumber; is equivalent to private string PhoneNumber;  protected – Protected members can be accessed only from the child classes.  internal – Internal members can be accessed from anywhere within the application. This is the default access specifier for a class.  protected internal – Similar to protected, protected internal members can be accessed from the child classes but only within the application. ල ෙගත්: Members඼ට එයා඼මේ Memeber functions ඕමන මල඼ාලක Acces කරන්න පුළුලනි. (Access Specifier එක කුමක් වුලත්.) අපි ගේ ෙැන පසුලටත් තල කතා කරමු...... ගේ නිදසුන බ඼න්න. ඔබ ගමය Type කර Run කරන්නට උත්සහ කරන්න. එන Errors අඳුනාගෙන Encapsulations අලගබෝධ කරෙන්න. class House { // Data Members public string DrawingRoom; private string Kitchen; // Member Functions private bool EnterDrawingRoom() { DrawingRoom = "The Drawing Room"; } public bool EnterKitchen() { Kitchen = "The Kitchen"; /* Even though Kitchen is declared Private, EnterKitchen function can modify it because the member function itself has access to all other members. */ } } class MainClass { public static void Main() { House TheBlackHouse = new House(); TheBlackHouse.DrawingRoom = "Main Drawing Room"; /* OK - Public Data Member is accessible from outside the class */ TheBlackHouse.Kitchen = "Main Kitchen"; /* Error - Private Data Member is not accessible from outside the class. */ TheBlackHouse.EnterDrawingR oom(); /* Error - Private Member Function is not accessible from outside the class. */ TheBlackHouse.EnterKitchen( ); /* OK - Public Data Member is accessible from outside the class. */ } } මීළඟ නිදසුන: Declaring a Method with a public Access Modifier: BankAccountPublic.cs using System; class BankAccountPublic { public decimal GetAmount() { return 1000.00m; } } The GetAmount() function is public. So, it can be called by code that is external to this class. Now, you can write the following code, elsewhere in your program, to use this function: BankAccountPublic bankAcctPub = new BankAccountPublic(); // call a public method/function decimal amount = bankAcctPub.GetAmount(); ඔබ සැමට 2012 ලසර ජයග්රාාහී ව ලසරක් ම ලා!!!!! - ෙරිඳු වීරසිංඳ මීෂඟ මකොටව ඼බන වතිමේ......... පරිගණක ඉංජිම් රු, ෙරිඳු වීරසිංඳ විසිනි
  • 11. OOP සරලව.... ENCAPSULATION තල දුරටත්..... මේ ලිපිය තුළිනුත් අපි සාකච්ඡා කරන්මන් ENCAPSULATION සංකල්ඳය තුළ ඇති විවිධ මයදීේ පිළිබ඲ලයි....ඳසුගිය සතිමේ ඳළවූ ලිපිමේ ඉදිරිඳත් ක඼ මේ ගැන ඔබට ම ො඲ අලමබෝධයක් ඇතැයි සිතනලා...එම ලිපිමේ අපි කතා ක඼ මේලල් මතක තබාමගන මේ ලිපිය ඳරිශී඼නය කරන්න! පසුගිය ලිපිය අලසන් කලේ public Access Modifier එක භාවිතා කරන ආකාරය ලපන්ලා ලෙමිනුයි. අෙ අපි මුලින්ම බ඼මු private Access Modifier එක භාවිතා කරන ආකාරය... Declaring a private Field: BankAccountPrivate.cs using System; class BankAccountPrivate { private string m_name; public string CustomerName { get { return m_name; } set { m_name = value; } } } අපි ඉහත get සහ set methods ල඼ට getter සහ setter methods කිය඼ කියනලා.....ඔබට ෙැකගන්නට පුළුලන් ලකොලහොමෙ අොළ Customer Name එක m_name කියන field එක තුළ අන්තර්ගත කර ඇති ආකාරය. ලහොඳින් බ඼න්න, m_name field එක, CustomerName කියන property එක තුළ සැඟවි඼යි තිලබන්ලන්. එනම් එය තමයි අප බ඼ාලපොරාත්තු ලලන ENCAPSULATION එක. m_name එක private ම඼ස declare කර ඇති නිසා මේ code එමකන් (BankAccountPrivate class එමකන්) එළිමේ ඔබට m_name එක access කරන්න බෑ, ඒ මලනුලට public CustomerName property එක පාවිච්චි කරන්න පුළුලන්. අපි ලම් විදිලහේ තල නිෙසුනක් බ඼මු. එවිට තලත් ලමය පැහැදිලි ලේවි ඔබට.... class Person { private int age; public int Age { get { return age; } set { age = value; } } } age එක public variable එකක් විෙහට තිබුනානම්, ඕලන් ලකලනකුට Main method එක තුළ පහත විදිහට age එක access කර඼ා අගයන් ලලනස් කරන්න පුළුලන්.... Person p = new Person(); p.age = -10; එතමකොට මමහි ENCAPSULATION එකක් නැ ැ....නමුත් දැන් මමහි ENCAPSULATION එකක් තිමබනලා....ඒ නිසා, age එක access කරන්මන් මමම මයි: Person p = new Person(); p. Age = -10; ඉහත Person Class එක අපට පහත පරිදි ඉතා සර඼ ආකාරයටත් ලියන්න පුළුලනි. (ඉහතින් ලිය තිබ්ලබන්ලන් C# හි සමහර සම්මත methods (default methods) එනම්, get, set සහ value ලයොොලගනයි. ඒලා ලයොොලනොලගන වුලෙ ENCAPSULATION සංකල්ඳය පහත ආකාරයට ඉදිරිපත් කරන්නට පුළුලනි. class Person { //Default value for the private variable. If not assigned it will be 0 private int age; //Method to Set the Age public void SetAge(int ageSet) { age = ageSet; } //Method to Get the Age public int GetAge() { return age; } } ලැදගත්: parameter එකක් විදි ට එලන variable එමක් නමත් (උ.දා. ageSet) private variable එමක් නමම නේ, (මේ නිදසුමන් නේ age) අඳට set method එමක්දී (මේ නිදසුමන් නේ SetAge() ) value එක assign කිරීමේදී this key word එක මයොදාගන්න මලනලා...( උ.දා.this.age = age;) ඊට අොළ Program Class එක: class Program { static void Main(string[] args) { Person p1 = new Person(); //Set Age p1.SetAge(35); //Get Age Console.WriteLine("nAge of the Person = " + p1.GetAge()); Console.ReadKey(); } } ඔබට හිලතනලා ඇති ලයසක් 0 ට ලඩා අඩු විය ලනොහැකි බල. ඒ නිසා 0 ට ලඩා අඩු අගයක් Age හි value එක ල඼ස කේරුහරි ඇතුේ කල඼ොත් එය ලැරදි බල අපට ලම් setter method එක තුලින්ම ලේනලා දිය හැකියි....ඊට අපි, validation එකක් යයි කියමු. ඔබට අල඾. පරිදි ලමලන් vaidations ලයෝොගාත හැකියි.......Encapsulation තුළින් ඼ැලබන තල ලාසියක් තමයි ඒ. පහත නිෙසුන ලමය ඔබට මනාලට කියා ලේවි.... class Person { //Default value for the private variable. If not assigned it will be 0 private int age=1; public int Age { get { return age;} set { if(value <0){ Console.WriteLine("nInvalid age! That age is: " + value); }else{ this.age = value; } } } } ඊට අොළ Program Class එක: class Program { static void Main(string[] args) { Person p1 = new Person(); Person p2 = new Person(); //Set Age p1.Age = 35; p2.Age = -20; //Get Age Console.WriteLine("nAge of Person1 = " + p1.Age); Console.WriteLine("nAge of Person2 = " + p2.Age); Console.ReadKey(); } } මීළඟ ලකොටස ඼බන සතිලේ.........
  • 12. පරිගණක ඉංජිනේරු, තරිඳු වීරසංශ විසනි OOP සරලව.... OOP හි තලත් ලැදගත් අංග කිහිපයක්.... නේ ලිපිය තුළිේ අපි වාකච්ඡා කරේනේ OOP වංකල්පය තුෂ ඇති, CLASSES වශ OBJECTS වමග වබැඳි තලත් වින඾ේ඿ නයදීේ කිහිපයක් පිළිබඳලයි.... COHESION & COUPLING Cohesion: මෙහිදී අදහස මෙමෙන්මන්, Class එෙක් කුෙක් මහෝ එක් වස්තුවෙට අදාළ, ගැළමඳන ොර්යයන් ස඲හා ඳෙණක් define ෙෙ තිබීෙයි. අපි හිතමු StudentDetails කියලා එෙක් ඔබ ලියනවා කියලා...එයින් ෙෙන්මන් Student Details Set ෙෙලා Print ෙෙන එෙ වමේ, Student Details වලට ඳෙණක් අදාළ වූ මේවල් නම්, ඔබ Cohesion සංෙල්ඳය අනුගෙනය ෙෙ තිමබනවා. Student Details Class එෙ තුළ ඔබ මවනත් Class එෙක් තුළ තිබිය යුතු Method එෙක් ලියා ඇත්නම්, [උදා: printSubjectList( ) වමේ, SubjectDetails වැනි Class එෙෙට අදාළ Method එෙක්] ඔබ Cohesion සංෙල්ඳය අනුගෙනය ෙෙ නැහැ. එය, සාර්ථෙ Class Design එෙක් මලස සැලමෙන්මන් නැහැ. ඳහත දක්වා ඇති උදාහෙණය මෙය වඩා මහොඳින් ඳැහැදිලි ෙෙනවා..... class StudentDetails { private String firstname; private String surname; private String street; private String city; /*Default Constructor*/ public StudentDetails() { } /*Method to set the name*/ public void setName(String f, String s) { firstname = f; surname = s; } /*Method to set the address*/ public void setAddress(String st, String c) { street = st; city = c; } /*Method to print the name*/ public void printName() { Console.WriteLine("Name: ", firstname, surname); } /*Method to print the address*/ public void printAddress() { Console.WriteLine("Street: ", street); Console.WriteLine("City: ", city); } } ඉහත StudentDetails Class එෙ Cohesion සංෙල්ඳය අනුගෙනය ෙෙ තිමබනවා. Cohesion is the Object Oriented principle which is making sure that a class is designed with a single, well focused purpose! The higher the Cohesion the “better”! Coupling: 1. Low Coupling: මෙෙගින් අදහස් මෙමෙන්මන් එෙ Class එෙෙට යම් මවනස් ෙෙක් ෙළමහොත් ඊට සම්බන්ධ අමනක් Classes වලට මවනසක් කිරීෙට අවශ්යන මනොීමෙයි. 2. High Coupling: මෙෙගින් අදහස් මෙමෙන්මන් එෙ Class එෙෙට යම් මවනස් ෙෙක් ෙළමහොත් ඊට සම්බන්ධ අමනක් Classes වලට ද මවනසක් කිරීෙට අවශ්යන ීමෙයි. Low Coupling is better than High Coupling! අපි Coupling ගැන නත්රුේ ගනිමු පශත උදාශරණනයේ: Classes නදක මුලින් තිබෙන විදිහ: class ContactDetails { private Phone phone; private String street; private String city; /* Constructor*/ public ContactDetails(Phone p, String s, String c) { phone = p; street = s; city = c; } /*Method to print*/ public void print() { Console.WriteLine("Street: ", street); Console.WriteLine("City: ", city); Console.WriteLine("Phone: ", phone); } /*Method to return city*/ public String getCity() { return city; } } class Phone { private int area; private int number; /*Constructor*/ public Phone(int a, int n, ContactDetails c) { area = a; number = n; validateArea(area, c.getCity()); } } *Note: validateArea ( ) method එෙ define ෙෙ නැති අතෙ මෙෙ සංෙල්ඳය ඳැහැදිලි කිරීෙට එහි අන්තෙගතය මෙහිදී අවශ්යනෙ නැත. ContactDetails constructor එනක් නලනව බ඼ේන: class ContactDetails { private Phone phone; private String street; private String city; /* Constructor*/ public ContactDetails(int a, int n, String s, String c) { validateArea(a, c); phone = new Phone(a, n); street = s; city = c; } .................... /*The other methods are the same*/ ..................... ඒ අනුල එක නලනව් වුනු ශැටි බ඼ේන: class Phone { private int area; private int number; /*Constructor*/ public Phone(int a, int n) { area = a; number = n; } } ලැදගත්: නමය නශොඳ Object Oriented Design එකක් නනනලයි.... මීළඟ මෙොටස ලබන සතියට.... class ContactDetails class Phone
  • 13. OOP වර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංශ විසනි ASSOCIATION, AGGREGATION, COMPOSITION OOP වංකල්පනේදී CLASSES අතර ඇති වම්බේධතා ගැන අපි අද කතා කරමු. ASSOCIATION: නෙෙ වම්බේධතානේදී අදාෂ CLASSES නදකට අයිති කරුනලක් නැති අතර නදකටෙ තොටෙ අනේනික ගති ඼ක්඿ණ පලතී. Association is a (*a*) relationship between two classes. It allows one object instance to cause another to perform an action on its behalf. Association is the more general term that defines the relationship between two classes. (*a*) - *has a* , *use a* basically it is a verb that we can use! උදාහරණය:  StudentRegistrar and RecordManager classes. (Relationship එක nssociation එකඑ ල඼ස අර්ථ දැඑවිය හැකි අතර ,StudentRegistrar uses a RecordManager ල඼ස කිල හැකිය). ලෙල඼ස ඉහත කී ලේ ලඳන්විය හැකිය. Code එක ගත්ලතොත්: public class StudentRegistrar { public StudentRegistrar (); { new RecordManager().Initialize(); } } AGGREGATION Special type of an association..... Aggregation is the (*the*) relationship between two classes. When object of one class has an (*has*) object of another, if second is a part of first (containment relationship) then we called that there is an aggregation between two classes. Unlike association, aggregation always insists a direction. Aggregation එකක් වින඾ේෂිත වූ Association එකකි. එය Association එකක් නශොඳිේ විව්තර කරයි. එයට ශැෙනල඼ානලෙ දි඾ාලක් තිනබනලා..... උදාහරණය: ලේ උදාහරණලේදී, අඳට කියන්න පුළුලන් University has a Chancellor or University aggregates Chancellor! කිය඼ා. Code එක ගත්ලතොත්: public class University { private Chancellor universityChancellor = new Chancellor(); } Note: Chancellor ලකලනඑ නැති උනත් University එකඑ තිබිය හැකිය. එනිසා තෙයි nggregation relationship එලඑ හිස ලකොටස University එක ලදසට තිලෙන්ලන්....ඔෙ Classes design කරේදී ලේ ලදය ෙතලඑ තො ගත යුතුයි....එවිට ඔෙට අතර නිලැරදි සේෙන්ධතාලන් ලගොඩ නැගිය හැකියි... COMPOSITION ඉහත උදාහරණයෙ ඉදිරියට ලගනයමින් අපි ලේ සේෙන්ධතාල ලත්රුෙ ගනිමු. Chancellor ලකලනඑ නැති උනත් University එකඑ තිබිය හැකිමුත් University එකඑ නැතුල එහි Faculties )පීඨ( තිබිය ලනොහැකිය.....ඒ ලලේ අලස්ථාලන් ල඼දී ලයලදන වම්බේධතා ල඼ට අපි Compositions යැයි කියනලා... ලහොඳින් ෙ඼න්න, Class Diagram එලඑ Faculty Class එක සහ University Class එක අතර ඇත්ලත් “University has Faculties” යන සේෙන්ධතාල වුලත් university එකඑ නැති විට faculty එකඑ ද නැති නිසා එහි ඊ හිස කළු ලර්ණලයන් යුතුල තිලෙනලා..... ලහො඲යි, අද අපි සර඼ල අලලෙෝධ කරගත්ලත්, CLnSSES ලගොඩ නැගීලේදී ලයොදාගැලනන සේෙන්ධතා ගැනයි.... අපි කතා කරපු ලේලල් සේපිණ්ඩනය කර ලඳන්වුලලොත් ඳහත සටහනින් එය ෙැනවින් විදුොන ලලයි..... මීළඟ ලකොටස ඼ෙන සතිලේ.........
  • 14. OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි GENERALIZATION OOP ල඼ Classes ල඼ ප ොදු ඼ක්ෂණ අනුල ඒලා සැකපසන ආකාරයක් ප඼ස GENERALIZATION හඳුන්ලමු.  Entities ල඼ ප ොදු ඼ක්ෂණ හඳුනාගැපන්. (Attributes පහෝ Behaviours පහෝ ඒ පෙපක්ම.  ඒ ප ොදු ඼ක්ෂණ ගසක ආකෘතියක් අනුල සැකපසේ. (Arranged in a Tree Structure)  උඩම ඇත්පත් root එකයි. එහි යටපත් ඇති සියලුම entities ල඼ ප ොදු ඼ක්ෂණ එය තුළ අඩංගු පලනලා. (ඉහත සටහනට අනුල, Ellipse සහ Polygon entities ල඼ට Shape entity එපක් ඼ක්ෂණ ඇති අතර Circle එකට Shape එපක් ඼ක්ෂණ ල඼ට අමතරල Ellipse එපක්ෙ ඼ක්ෂණ ඇත.Rectangle එකට Shape එපක් ඼ක්ෂණ ල඼ට අමතරල Polygon එපක්ෙ ඼ක්ෂණ ඇත.  පේ ආකෘතියට Generalization/Inheritance Hierarchy යැයි කියමු. INHERITANCE ප්රEමුඛතම Entity එපක් සිට (Root or Super Class) හ඼ට ඼ක්ෂණ පප්රEේරණය ම ම පමපසේ හඳුන්ලමු. Extending Classes කලිේ අර්ථ දැක්වූ Class ලලිේ අලුත් Classes නිර්මාණය කිරීම. In OOP inheritance is a way to form new classes using classes that have already been defined. Super Class ආකෘතිනේ මුලිේම ඇති Class එකයි. The class from which the subclass is derived is called a super class (also called as base class or parent class) Sub Class ආකෘතිනේ මුලිේම ඇති Class එක යටනත් ඇත... A class that is derived from another class is called a subclass (derived class, extended class, or child class) INHERITANCE දක්නට ඼ැනෙන ආකාර ල඼ උදාහරණ: අපි පේ එක එකක් ගැන (Inheritance Types) ඊළඟ ලිපිපයන් කතා කරමු. අෙ මම Simple Inheritance එකකට උොහරණයක් පගන එන්නේ: (Sphere class එක Circle class එක Extend කර ඇති අයුරු බ඼න්න.....) Source File: Circle.cs namespace FlatShapes { class Circle { private double _radius; public double Radius { get { return (_radius < 0) ? 0.00 : _radius; } set { _radius = value; } } public double Diameter { get { return Radius * 2; } } public double Circumference { get { return Diameter * 3.14159; } } public double Area { get { return Radius * Radius * 3.14159; } } } } Source File: Sphere.cs namespace Volumes { class Sphere : FlatShapes.Circle { new public double Area { get { return 4 * Radius * Radius * 3.14159; } } public double Volume { get { return 4 * 3.14159 * Radius * Radius * Radius / 3; } } } } Source File: Exercise.cs using System; using Volumes; using FlatShapes; class Exercise { static void Show(Circle round) { Console.WriteLine("Circle Characteristics"); Console.WriteLine("Side: {0}", round.Radius); Console.WriteLine("Diameter: {0}", round.Diameter); Console.WriteLine("Circumference : {0}", round.Circumference); Console.WriteLine("Area: {0}", round.Area); } static void Show(Sphere ball) { Console.WriteLine("nSphere Characteristics"); Console.WriteLine("Side: {0}", ball.Radius); Console.WriteLine("Diameter: {0}", ball.Diameter); Console.WriteLine("Circumference : {0}", ball.Circumference); Console.WriteLine("Area: {0}", ball.Area); Console.WriteLine("Volume: {0}n", ball.Volume); } public static int Main() { FlatShapes.Circle c = new FlatShapes.Circle(); Volumes.Sphere s = new Volumes.Sphere(); c.Radius = 20.25; Show(c); s.Radius = 20.25; Show(s); return 0; } }
  • 15. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි INHERITANCE තව දුරටත්...... Simple/Single Inheritance: Note: Super Class එකේ properties Derived Class එකට ඼ැකෙන නිසා ඒලා අලුකෙන් ලිවිය යුතු නැති අෙර reuse කළ හැකිය. Class එකේ ෙනි Super Class එකකින් අභා඾ය ගනී නම්, නැෙකහොත් Derive වුනි නම්, එය Single Inheritance කලයි. ක ොදුකේ Inheritance සංකල් ය තුළ, Access Specifiers කයකෙන ආකාරය හෙ සටහනින් කහොඳින් ක න්ලයි. ඔෙ එහි ඊෙ඼ දි඾ා කෙස කහොඳින් ෙ඼ා එය කත්රුම් ගන්න. Simple Inheritance සඳහා උොහරණයේ: Super Class එක: Derived Class එක: Hierarchical Inheritance කෙය ඉොෙ ෙහු඼ල භාවිො ලන Inheritance ලර්ගයයි. සටහන ෙ඼න්න. කෙය Hierarchial Inheritance සංකල් යය සර඼ල ක න්ලා කෙයි. සුල ෙේලා ඇති C# Class Diagram එක සහ Coding ෙ඼න්න. C# Class Diagram එක: C# Class Code එක: Super Class: class sampleShape { public virtual int area() { Console.WriteLine("Virtual method area of the base class"); return 0; } } Derived Class1: class sampleRectangle : sampleShape { private int arg1, arg2; public sampleRectangle(int arg1, int arg2) { this.arg1 = arg1; this.arg2 = arg2; } public override int area() { return (arg1 * arg2); } } Derived Class2: class sampleTriangle : sampleShape { private int arg1, arg2; public sampleTriangle(int arg1, int arg2) { this.arg1 = arg1; this.arg2 = arg2; } public override int area() { return ((arg1 / 2) * arg2); } } Test Class: class testClass { static void Main(string[] args) { sampleShape obj1 = new sampleRectangle(10,20); int result1 = obj1.area(); sampleShape obj2 = new sampleTriangle(10,20); int result2 = obj2.area(); Console.WriteLine("Area of Rectangle:{0} nArea of Triangle:{1}", result1, result2); Console.ReadKey(); } }
  • 16. OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි INHERITANCE තල දුරටත්...... Identifying a valid Inheritance Hierarchy OOP සංකල්පයේට අනුල ලැඩසටහේ ලිවීනේදී අප නිලැරදි Inheritance ආකෘති හඳුනාගේනට අල඾ප නලනලා...ඒ සඳහා සර඼ රීතියක් තිනෙනලා....එය හඳුේලේනේ ‘is a’ rule කිය඼යි.... Subclass එකෙන් නිරූපිත object එෙ ‘is a’ සම්බන්ධය කයොදා Superclass එෙ සමග ඈ඲ා බ඼ා, එම සම්බන්ධය ඳලතී නම් එය නිලැරදි Inheritance එෙක් ක඼ස හඳුනාගනිමු. ඉහත සටහකන් දැක්කලන Inheritance යතාර්ථලාදීදැයි බ඼මු:  Region is a Country  False  Car is a Vehicle  True  Mouse is a Computer  False  Circle is a Shape  True ඒ අනුල, ඳළකලනි සහ තුන්කලනි Inheritance යතාර්ථලාදී කනොලන අතර (Invalid) කදලන සහ හතරලන යතාර්ථලාදී (Valid) කලයි.... Types of Inheritance in C# ඔබ දැන් දන්නලා ඉහතින් දැක්කලන්කන් Simple Inheritance ආෙෘතියක් බල. C# තුළ, Simple Inheritance සහ Hierarchial Inheritance නිර්මාණය ෙළ හැකිමුත් ඳහතින් සටහනින් දැක්කලන Multiple Inheritance නිර්මාණය ෙළ කනොහැකිය. එය ෙළ හැකි ලන්කන් Interfaces භාවිතා ෙරමින්ය....(අපි ඒ ගැන Interfaces ගැන ඉකගන ගන්නාවිට අලකබෝධ ෙරගනිමු.) METHOD OVERRIDING මීට ෙලින්, METHOD OVERLOADING ගැන මම කියා දුන්නා මතෙ ඇති. (එෙම Class එෙ තුළ එෙම method name එෙ සහිත නමුත් parameters කලනස් method ඳැලතීම METHOD OVERLOADING කලයි.) METHOD OVERRIDING ගැන ෙතා ෙළ හැකිලන්කන් අපි Inheritance ඉකගන ගත්තායින් ඳසුලයි. ඒ කමොෙද කිව්කලොත්, Inheritance කනොමැතිල METHOD OVERRIDING ඳැලතිය කනොහැකි බැවිනි. Usage of ‘Method Overriding’ is enabling the sub class to provide a specific implementation of a method that is already provided by one of its super class(es) METHOD OVERRIDING තුළින් ලන්කන්, Super Class එකක් අර්ථ දක්ලා ඇති (defined) method එෙක් Sub Class එෙ තුළ එහි ොර්යයන් සම්පූර්ණකයන්ම කගොඩනැගීමයි. ඒ ස඲හා විවිධ programming langauges විවිධ syntaxes භාවිතා ෙරනලා. ඒ අතරින් C# , super class එකක් virtual නමැති keyword එෙත් sub class එකක් override keyword එෙත් කයොදාගන්නලා... ඳහත නිදසුන බ඼න්න: public class Animal { public virtual void eat(){ Console.WriteLine("Animal Eating"); } } public class cat : Animal{ public override void eat(){ Console.WriteLine("Cat Eating"); } } Note: Sub class එනක් overidden method එනක් නමත්, parameters ගණනත් Super class එනක් virtual method එකට සමාන විය යුතුයි. METHOD OVERRIDING ල඼ට සර඼ උදාහරණයක් සමගින් අද ඳාඩම අලසන් ෙරමු. (Square - super class; Cube - sub class) using System; class TestMehtodOverriding { public class Square { public double x; // Constructor: public Square(double x) { this.x = x; } public virtual double Area() { return x*x; } } class Cube: Square { // Constructor: public Cube(double x): base(x) { } // Calling the Area base method: public override double Area() { return (6*(base.Area())); } } public static void Main() { double x = 5.2; Square s = new Square(x); Square c = new Cube(x); Console.WriteLine("Area of the Square = {0:F2}", s.Area()); Console.WriteLine("Area of the Cube = {0:F2}", c.Area()); } }
  • 17. OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි ABSTRACT CLASSES & METHODS න ොනලද නේ ABSTRACT CLASSES? කෙටිකෙන් ම කිවක ොත්, සම්පූර්ණ නැති methods ඇති, එම methods, derived class තුළදී සම්පූර්ණ ෙළ යුතු ආොරකේ classes කමනමින් ැඳින්කේ... ABSTRACT CLASS එකක ඼ක්ෂණ අපි පහත පරිදි හඳුනාගනිමු:  Can have one or more incomplete (abstract) methods  Cannot be used to instantiate objects  Normally used as base-classes in inheritance hierarchies  Derived classes called concrete classes must define the missing pieces  Can have instances from the Derived classes Abstract methods එෙෙට වැඩි ගණනක් තිබිෙ ැකි අතර කමම classes වල Objects ැදිෙ කනො ැකිෙ. Inheritance Hierarchies වල Base Class එෙ කලස ක ොක ෝවිට කෙොදා ගැකනන්කන් කමවන් Abstract Classes ෙ. න ොනලද නේ ABSTRACT METHODS? සම්පූර්ණ නැති methods නැත්නම් Abstract Class එෙෙ abstract key word එකෙන් ඳුන්වා ඇති methods කමනමින් ැඳින්කේ. ABSTRACT METHOD එකක ඼ක්ෂණ අපි පහත පරිදි හඳුනාගනිමු:  Only the method signature is there. Abstract method declarations are only permitted in abstract classes  Mark with the keyword abstract and a semicolon at the end  Implementation is missing  Does not know how to implement the method කම්වාකේ ඇත්කත් method signature එෙ පමණි. රෙ නැත්නම් මදෙ ඇත්කත් derived class එකක්ෙ. ABSTRACT CLASSES සහ METHODS ල඼ට උදාහරණ පිරික්සමු: public abstract class Shape { public abstract void Paint(Graphics g, Rectangle r); } public class Ellipse: Shape { public override void Paint(Graphics g, Rectangle r) { g.DrawEllipse(r); } } public class Box: Shape { public override void Paint(Graphics g, Rectangle r) { g.DrawRect(r); } } ප ත ආොරෙ වැරදිෙ....compilation error එෙක් කේවි: abstract class AbstractBase { public abstract void F(); } class SubClasss: AbstractBase { public override void F() { base.F(); // Error, base.F is abstract } } An abstract method declaration is permitted to override a virtual method. This allows an abstract class to force re-implementation of the method in derived classes, and makes the original implementation of the method unavailable. In the examples: Abstract method එකක් තල යේ class එකක ඇති virtual methods override කළ හැකි ලන පරිදි සකසා ඇත. පහත උදාහරණ බ඼ේන: using System; class A { public virtual void F() { Console.WriteLine("A.F"); } } abstract class B: A { public abstract override void F(); } class C: B { public override void F() { Console.WriteLine("C.F"); } } public class D { public virtual void DoWork(int i) { // Original implementation. } } public abstract class E : D { public abstract override void DoWork(int i); } public class F : E { public override void DoWork(int i) { // New implementation. } } Abetract Methods, Classes ස ඒවා සම් න්ධ කේ ගැන අපි ල න සතිකෙත් වැඩිදුර ෙතා ෙරමු.
  • 18. OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි ABSTRACT CLASSES & METHODS (CONT.) ABSTRACT CLASSES & METHODS නහොඳිේ නේරුම් ගේනට අපි අද තලේ උදාහරණයක් නදස බ඼මු: අදාළ CLASS DIAGRAM එක: CarFactory.cs: SportsCar.cs: DRIVER CLASS  Driver.cs: GENERIC FACTORY CLASS  GenericFactory.cs ඉහත දැක්වූ ABSTRACT CLASSES ලලිේ ලැඩක් ගේන CLASS එක නෙයයි: නෙෙ උදාහරණය හරහා ෙට අල඾ය වූනේ ABSTRACT CLASSES නයනදේනේ කුෙන ආකාරනයේදැයි ලඩාේ පැහැදිලි කිරීෙටයි. නෙහි එන සෙහර නේලල් ගැන අපි පසුලට කතා කරමු. (උ.දා. Generics) Output of this example:
  • 19. OOP සරලව.... DYNAMIC BINDING What is Dynamic Binding and static binding ? In Dynamic Binding, objects are bound to the reference object on runtime where as in Static Binding the compiler is straight away aware of which object is bound before runtime. උදාහරණ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Inheritance { using System; using System.Collections.Generic; namespace TestingSolutions { public class Animal { public virtual void eat() { Console.WriteLine(" Animal Eating"); } } public class Cat : Animal { public override void eat() { Console.WriteLine(" Cat Eating"); } public void eat(String s) { Console.WriteLine(" Cat Eating" + s); } } class testDynamicBinding { static void Main(string[] args) { //Test-1 Animal a = new Animal(); a.eat(); //Test-2 Cat c = new Cat(); c.eat(); //Test-3 Animal ac = new Cat(); ac.eat(); //Test-4 Cat c1 = new Cat(); c1.eat(" Meat"); //Test-5 : Gives Errors (Animal class's eat() method does not take arguements) Animal a2 = new Animal(); a2.eat(" Meat"); //Test-6 : Gives Errors (Cat object of Animal type also does not have an eat() method to take args) Animal ac1=new Cat(); ac1.eat(" Meat"); //Test-7: Syntactically this is wrong: Can't convert a lower type reference to a higher type in the hirachcy Cat myCat = new Animal(); Console.ReadKey(); } } } } තවත DynamicBinding.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class DynamicBinding { public virtual void abcd() { Console.Write("In base classn"); } } // This is the junior class class DBInherit : DynamicBinding{ public override void abcd() { Console.Write("In junior classn"); } public void abcd2() { Console.Write("In junior classn"); } } } Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class Program { static void Main(string[] args) { #region This code is used to show the dynamic binding DynamicBinding _objDB = new DynamicBinding(); _objDB.abcd(); DynamicBinding _objDB2 = new DBInherit(); //This is an example of Dynamic Binding as the compiler did'nt know if there is a method overriding the base class method _objDB2.abcd(); Console.ReadKey(); #endregion } } } OUTPUT
  • 20. OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි Reference Variable Casting පසුගිය වතියේ අපි කතා කයේ Dynamic Binding ගැනයි. යේ වතියේදී අපි Reference Variable Casting ගැන කතා කරමු. ඔබ දන්නලා, OOP හි ප්රයධානත වකකේපයක් Inheritance ශරශා අපි Super Class එයක් සිට Junior Class එකට ඼ක්඿ණ යප්රයහරණය වී අපි ඉයගන ගත්තා... Inheritance ගැන ඉයගන ගත්තායින් අනතුරුල අපි Method Overriding, Abstract Methods/Classes වශ Dynamic Binding ඉයගන ගත්තා. ඒලා සියේ඼ Inheritance ව ග එකට බැඳුණු යේලේය.....ඉතින්, අදත් අපි Inheritance ව ග වබැඳි තලත් එලැනි ලැදගත් යදයක් ලන Reference Variable Casting ගැන ඉයගන ගනිමු. එක ලර්ගයක Object එකක් තලත් ලර්ගයකට සමාන කිරීනේදී නමම Casting ක්රරමය නයොදා ගැනේ. තලත් විදිහකිේ කිව්නලොත්, එක class එකකට reference එකක් ඇති object එකක්, තලත් class එකකට reference එකක් ඇති object එකක් සමග සේබේධ කිරීමට Casting කිරීම නයොදා ගැනේ! Casting ලර්ග නදකක් තිනබනලා...  Up-Casting:  Assign the SUB class reference to a SUPER class reference.  Always SAFE!  Implicit cast  Down-Casting:  Assign the SUPER class reference to a SUB class reference.  Always not an safe operation  Need an explicit cast Up-casting ල඼දී, අපි SUB class reference එකක් SUPER class reference එකකට ව ාන කරනලා, නැත්නේ වේබන්ධ කරනලා...එය වා ානd යදයක්. එනේ ‘Up-casting’ කිසිඳු ගැටළුලක් නැතිල පාවිච්චි කරන්නට පුළුලන්. Down-casting ල඼දී, අපි SUPER class reference එකක් SUB class reference එකකට ව ාන කරනලා, නැත්නේ වේබන්ධ කරනලා...එය නේ එතරේ වා ානd යදයක් යනොයලයි. ඒ කියන්යන්, ‘Down-casting’ එතරේ ආරක්ෂිඒත ලන්යන් නැශැ.... නේ නලනස්කේ නත්රුේ ගනිමු අපි පුකචි උදාශරණයක් තුළින්.... සිතන්න Car වශ Van classes යදක Vehicle super class එයකන් inherit යලනලා කිය඼ා...ය න්න යේ විදිශට : එතනකොට Up-casting කියන්යන් යේ ලයේ අලව්ථාලකට: Vehicle එකක්, Car එකක් විය ශැකිය. එනේ, ඕයන යල඼ාලක ය඼ොකු යදයක් යපොඩි යේකට වේබන්ධ කෂ ශැකිය.  Down-casting කියන්යන් යේ ලයේ අලව්ථාලකට, තුන්යලනි යේලියේ ඇත්යත් Down-casting එකයි: (ඔබට හියතනලා ඇති යදලන යේලියේ තියයන්යන් Up-casting එකක් යන්ද කිය඼ා....එයශ හිතුනනේ ඔබ ශරි!) ‘v1’ න ැති Van එකට ‘h’ න ැති Vehicle එක assign කරන්නට යපර ‘h’ ට තියබන්යන් Vehicle ඼ක්඿ණ වුලත් (‘h’ ට තියබන්යන් Vehicle reference එකක් වුලත්) ‘v’ න ැති Van object එක එයට assign කර තියබනලා...එබැවින්, ඔබට ‘v1’ න ැති Van එකට ‘h’ න ැති Vehicle එක assign කරන්නට අල඾d නේ, ‘h’ ල Van එකක් කර assign කෂ ශැකියි... නමුත් පශත ය඼ව ඔබ Code එක ලිව්යලොත් runtime exception එකක් එනලා...(Type කර Run කර බ඼න්න) Vehicle h = new Vehicle(); Van v1 = (Van) h; ඊට යශහතුල ත යි super class object එකක් යකලින් sub class object වේබන්ධ කිරී ට යනොදී . එයවහ කරන්නට නේ ඊට කලින් h ල Van object එකකට ව ාන කෂ යුතුයි. (ඉශත උදාශරණයේ යපන්ලා ඇති පරිදි) අපි දැන් තලත් උදාශරණයක් යලත අලධානය යයොමු කරමු. එය ඔබට ය Casting ගැන ලැඩි දුරටත් කියා යදයි: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Casting { class Program { class Animal { public void Eat() { Console.WriteLine("Eating."); } public override string ToString() { return "I am an Animal."; } } class Reptile : Animal { } class Mammal : Animal { } class ShowCasting { static void Main() { Mammal myMammal = new Mammal(); /*This is an implicit cast: i.e. Up-casting*/ Animal tiger = myMammal; /*This is an explicit cast: i.e. Down-casting*/ Mammal otherMammal = (Mammal)tiger; //Test-1 Test(new Reptile()); //Test-2 Test(new Mammal()); //Test-3 Test(new Animal()); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } static void Test(Animal a) { // Cause InvalidCastException at run time in Test-2 & 3 // Because Mammal & Animal is not convertible to Reptile respectively. Reptile r = (Reptile)a; } } } }
  • 21. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි POLYMORPHISM අපි, නේ වනනතක්, ලිපි දහඅටක් පුරාවට OOP සේබේධ වැදගත් සංකල්ප පිළිබඳව කරුණු සාකච්ඡා කළා.... අද ලිපිනෙේ අපි කතා කරේනේ OOP හි තවත් වැදගත් අංගෙක් වන POLYMORPHISM ගැනයි.... Polymorphism, Inheritance සමග එකට සේබේධව පවතිනවා... Inheritance නනොමැතිව Polymorphism පැවතිෙ නනොහැකියි… Polymorphism is the idea of allowing the same code to be used with different types, which allows us to write more generic and abstract implementations when we write computer programs using OOP concepts. The phrase "poly" implies "many" "morph" implies "appearance" මූලිකව Polymorphism වර්ග 3 ක් තියෙනවා. 1. Polymorphism based on Inheritance 2. Polymorphism based on Interfaces 3. Polymorphism based on Abstract classes (Interfaces Abstract classes පවතින්යන්ත් පැවතුයනොත් පමණයි.....නමුත් ඒවා Inheritance තුළ ඇති විය ේෂ අවස්ථා නිසා Polymorphism තුළ යකොටස් යෙකක් යෙස අපි ඉයගන ගනිමු...) අද ලිපිනෙේ අපි Polymorphism based on Inheritance ගැන දැනගනිමු.... අපි උදාහරණෙකිේ නේ ගැන අවනබෝධෙක් ඇති කරගනිමු. හිතන්න Account කිෙෙ Super Class එකක් තියෙනවා කිෙෙ...අපි ෙන්නවා බැැංකුවෙ Accounts වර්ග කීපෙක් තියෙනවා. යේ උොහරණයේදී අපි හිතමු වර්ග යෙකක් තියෙනවා කිෙෙ.....Savings සහ Current යේ වර්ග යෙයක් තැන්පතු සහ ආපසු ගැනීයේ ක්රිeොවනන් එකියනකට යවනස්! ඒ නිසා, implementation එකත් යවනස් යවනවා...Super Class (Account) එයක් virtual methods override කර තමන්ට අව c ය Derived Class එක තුළ implement කරගන්න යවනවා.....ඇත්යතන්ම අපි යේවා, Method Overriding ඉයගන ගන්නයකොට සරෙව කතා කළා.....ඉතින් ඒ සැංකල්පෙ අෙ, Polymorphism based on Inheritance යෙස අපි හඳුනාගන්නවා....පහත Coding නිෙහයසේ අධ්යcනෙ කරන්න… Account.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class Account { protected string name; protected float balance; //Constructor public Account ( string name, float balance ) { this.name = name; this.balance = balance ; } //Method for deposites public virtual void deposit ( float amount ) { balance += amount; } //Method for withdraws public virtual void withdraw(float amount) { balance -= amount; } //Display the summary public virtual void display( ) { Console.WriteLine ( "Name: {0} Balance: {1}", name, balance ) ; } } } SavingAccount.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class SavingAccount : Account { static int accno = 10100 ; int trans ; public SavingAccount ( string s, float b ) : base ( s, b ) { trans = 0 ; accno++ ; } public override void withdraw ( float amount ) { if ( trans >= 3 ) { Console.WriteLine ("Number of transactions exceed 3" ) ; return ; } if ( balance - amount < 100 ) Console.WriteLine ( "Below minimum balance!" ) ; else { base.withdraw ( amount ) ; trans++ ; } } public override void deposit(float amount) { if ( trans >= 3 ) { Console.WriteLine ( "Number of transactions exceed 3" ) ; return; } base.deposit ( amount ) ; trans++ ; } public override void display() { Console.WriteLine ( "Name: {0} | Account no.: {1} | Balance: {2}",name, accno, balance ) ; } } } CurrentAccount.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class CurrentAccount : Account { static int accno = 20200 ; public CurrentAccount ( string s, float b ) : base ( s, b ) { accno++ ; } public override void withdraw(float amount) { if ( balance - amount < 0 ) Console.WriteLine ( "No balance in account" ) ; else balance -= amount ; } public override void display() { Console.WriteLine ( "Name: {0} | Account no.: {1} | Balance: {2}",name, accno, balance ) ; } } } Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class Program { static void Main(string[] args) { #region This code is used to show polymorphism SavingAccount mySavingsAccount = new SavingAccount ( "Sunil", 10000.00f ) ; mySavingsAccount.display(); mySavingsAccount.deposit(25000); mySavingsAccount.display(); Console.WriteLine("n"); CurrentAccount myCurrentAccount = new CurrentAccount("Indika", 50000.00f); myCurrentAccount.display(); myCurrentAccount.withdraw(2500); myCurrentAccount.display(); Console.ReadKey(); #endregion } } } ලබන සතිනේ තවත් නේ ගැන කතා කරමු.... ඔබ සැමට සාමෙ සතුට පිරි සුභ නව වසරක් නේවා!
  • 22. OOP සර඼ල.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි POLYMORPHISM(තල දුරටත්) පසුගිය සතිනේ ඉදිරිපත් කළ program එනේ output එක: අද අපි කතා කරන්නන් Interface Based Polymorphism ගැනයි. Inheritance තුළින් ලනේම තුළින් ද Polymorphism සංකල්පය නගොඩ නැගිය හැකිය.....Interfaces ගැන අපි පසුලට කතා කරමු....දැනට අපි එනසේ නම් ක඼ හැකි Class එකක් තිනෙනලා යයි හිතමු (Interfaces ගැන මම මීළඟ ලිපි ලලින් කියා නදන්නම්) Class Diagram: IPrint Interface: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { public interface IPrint { void Print(); } } නම් IPrint Interface එක පහත දක්ලා ඇති InventoryItems සහ Personnel නදනකන් access කළ හැකිය.... අපි දැන් IPrint interface එක InventoryItems සහ Personnel classes තුළ implement කරමු. InventoryItems.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { public class InventoryItems<list> : List<list>, IPrint { public void Print() { foreach (list obj in this) { Console.WriteLine("Inventory Item: " + obj); } } } } Personnel.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { public class Personnel<list> : List<list>, IPrint { public void Print() { foreach (list obj in this) { Console.WriteLine("Person: " + obj); } } } } නම් classes නදක නයොදානගන අපි Program class එනක් TestIPrintInterface method එක ලියමු.... Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class Program { static void Main(string[] args) { TestIPrintInterface(); Console.ReadKey(); } #region This region is used to show interface based polymorphism public static void TestIPrintInterface() { // Create an InventoryItems object and populate it. IPrint obj = new InventoryItems<string>(); ((InventoryItems<string>)obj).Add("Pen") ; ((InventoryItems<string>)obj).Add("Book" ); // Print this object. CommonPrintMethod(obj); Console.WriteLine(); // Create a Personnel object and populate it. obj = new Personnel<string>(); ((Personnel<string>)obj).Add("Sumana"); ((Personnel<string>)obj).Add("Mallika"); // Print this object. CommonPrintMethod(obj); } private static void CommonPrintMethod(IPrint obj) { Console.WriteLine(obj.ToString()); obj.Print(); } #endregion } } Output: ඼බන සතිනේ තලත් නේ ගැන කතා කරමු....
  • 23. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි POLYMORPHISM(තව දුරටත්) පසුගිය සතිනේ අපි කතා කන ේ Interface based Polymorphism ගැනයි. අද අපි තුේවන Polymorohism type එක ගැන කතා කරමු...ඒ, Abstract Classes based Polymorohism ගැනයි... ඔබට මතකනම්, අපි Abstract Classes සහ Methods ගැන කතා කන ේ 15වැනි ලිපිය හරහායි...එහිදී කතා ක නේවල් යලි මතකයට ගතයුතු නවනවා... අපි නම් ගැන නවනදා වනේම උදාහරණයක් නයොදා නගන නත්රුම් ගනිමු. පහත Class Diagram එක බලේන: ‘Shape’ Class එක base class එක වී, Circle සහ Square classes නදක එමගිේ inherit වී ඇත. මුලිේම බලමු Abstract Class එකක් නනොමැතිව සාමාන නයේ අපි code ලියන ආකාරය: Shape.cs: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AbstractPolymorphism { class Shape { protected int x; protected int y; public Shape() { } public Shape(int x, int y) { this.x = x; this.y = y; } public virtual void Draw() { Console.WriteLine("Drawing a SHAPE at {0},{1}", this.x, this.y); } } } Square.cs: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AbstractPolymorphism { class Square : Shape { protected int xSquare; protected int ySquare; public Square(int x, int y) { xSquare = x; ySquare = y; } public override void Draw() { Console.WriteLine("Drawing a SQUARE at {0},{1}", xSquare, ySquare); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; Circle.cs: namespace AbstractPolymorphism { class Circle : Shape { protected int xCircle; protected int yCircle; public Circle(int x, int y) { xCircle = x; yCircle = y; } public override void Draw() { Console.WriteLine("Drawing a CIRCLE at {0},{1}", xCircle, yCircle); } } } Program.cs: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AbstractPolymorphism { class Program { static void Main(string[] args) { Shape myShape = new Shape(100, 100); Circle myCircle = new Circle(200, 200); Square mySquare = new Square(300, 300); myShape.Draw(); myCircle.Draw(); mySquare.Draw(); Console.ReadKey(); } } } Output: දැන් Shape class එක abstract කළ ොත් Draw() method එක ‘abstract class based polymorphism’ යටළත් භාවිතා ක හැකිය. මතක තබා ගන්න, අපට abstract class එකක instances හදන්නට බැහැ. එනිසා Program class එක තු code ලියන විදිහ ළෙනස් ළෙනො... Abstract class එක: namespace AbstractPolymorphism { abstract class Shape { protected int x; protected int y; public Shape() { } public Shape(int x, int y) { this.x = x; this.y = y; } public abstract void Draw(); } } අපි child classes ළදක ළෙනස් කරන්ළන් නැහැ...Abstract ළෙස define වී ඇති Draw() method එක ආකාර ළදකකින් භාවිතා වීමක් ඔබ දකිනො...(කලින් දැක්ළක් inheritance based polymorphism ළෙස, දැන් දකින්ළන් abstract class based polymorphism ළෙසයි.) ළමන්න Program.cs එක ළෙනස් ෙන අයුරු: namespace AbstractPolymorphism { class Program { static void Main(string[] args) { Shape[] shapes = new Shape[2]; shapes[0] = new Square(200, 200); shapes[1] = new Circle(300, 300); foreach (Shape shape in shapes) shape.Draw(); Console.ReadKey(); } } }
  • 24. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි INTERFACES අද අපි කතා කරන්නන් Interfaces ගැනයි....Polymorphism ගැන කතා කරද්දී මම Interfaces නයොදානගන උදාහරණයක් ඉදිරිපත් කළා මතක ඇති.....අපි අද Interfaces ගැන සවිස්තරව කතා කරමු. විවිධ ආකාරනේ classes අතර ඇති නමොන යම් නහෝ සමානකමක් නිනයෝජනය කරන්නට Interfaces නයොදාගන්නවා....එනසේ නයොදා ගත්තත් ඒ classes සම්බන්ධතා නගොඩ නැගීම Interfaces වල අනිවාර්ය වගකීමක් නනොනවයි.... උදාහරණයක් සිතමු. Car Tyre class එකක් සහ Tennis Ball class එකක් තිනයනවා කියල සිතන්න....Tyre එකක් (Car Tyre class object එකක්) සහ Tennis Ball (Tennis Ball class object එකක්) එකක් යන නදකටම නපොදු වූ ලක්ෂණයක් තමයි Bouncing feature එක...අපි හිතමු එය Bouncable කියල හඳුන්වනවා කියල. ඉතින්, ඉහත කී classes නදක ඒ ලක්ෂණය හරහා සම්බන්ධ කර ගත යුතු නම් අපිට 'Bouncable' කියල Interface එකක් ලියන්නට පුළුවන්! සාමාන නයන් අපි Interfaces ලියන නකොට ඉස්සරහට 'I' නයොදා ලියනවා, නමොකද එතනකොට පහසුනවන් එය Interfaces එකක් කියල බලු බැල්මට හඳුනාගන්න නල්සි නිසා… උදා. interface IBounceable { void bounce(); void setBouncingFactor(int bf); } class TennisBall : IBounceable{ private int bounceFactor; public void bounce(){ ………………… } public void setBouncingFactor(int bf){ ………………… } } class CarTyre : IBounceable{ private int bounceFactor; public void bounce(){ ………………… } public void setBouncingFactor(int bf){ ………………… } } අපි උදාහරණයක් නදස බලමු: IAnimal.cs using System; using System.Colle ctions.Generic; using System.Linq; using System.Text; namespace ForVidusara { interface IAnimal { string Name { get; set; } string Describe(); } } Dog.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class Dog : IAnimal { private string dogName; //Constructor public Dog(string dogName) { this.dogName = dogName; } //Implementation of the method declared in the Interface IAnimal public string Describe() { return "Hello, I'm a dog and my name is " + this.dogName; } //Getter and Setter methods implemented here (this is also an interface member) public string Name { get { return dogName; } set { dogName = value; } } } } Cat.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class Cat : IAnimal { private string catName; //Constructor public Cat(string catName) { this.catName = catName; } //Implementation of the method declared in the Interface IAnimal public string Describe() { return "Hello, I'm a cat and my name is " + this.catName; } //Getter and Setter methods implemented here (this is also an interface member) public string Name { get { return catName; } set { catName = value; } } } } Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class Program { static void Main(string[] args) { List<Dog> dogs = new List<Dog>(); List<Cat> cats = new List<Cat>(); //Add dogs dogs.Add(new Dog("Burampi")); dogs.Add(new Dog("Walgakota")); //Add cats dogs.Add(new Dog("Ngawwa")); dogs.Add(new Dog("Walgakota")); foreach (Dog dog in dogs) Console.WriteLine(dog.Describe()); foreach (Cat cat in cats) Console.WriteLine(cat.Describe());
  • 26. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි INTERFACES (තව දුරටත්) පසුගිය සතියේ ඉදිරිපත් කළ program එයේ output එක: යේ සතියයත් අපි Interfaces ගැනම කතා කරමු....ඒ ගැන වැඩි යතොරතුරු ඉයගන ගනිමු. Interfaces භාවිතනේ ඇති වාස: Interfaces තුළ ඇත්යත් declarations (methods, events, indexers and/or properties) පමණයි. Interfaces තුළ declarations පමණේ ඇත්යත් ඒවා inherited classes මගින් ඒ ඒ class එකට අනුකූල විදිහට implement කරන නිසායි.... ඉතින් implementations නැති නේ Interfaces වල ඇති වැදගත්කම යමොකද්ද ? නිතර යවනස් වන ලේෂණ ඇති Components එකට සේබන්ධ කරන්නට යයොදාගන්යන් Interfaces .... නිතර යවනස් වන ලේෂණ ඇති Components එකට සේබන්ධ කරන්නට යයොදාගන්යන් Interfaces .... එකම interface එක use කරන components extra programming නැතුව සේබන්ධ කර ගත හැකියි…. ඒ නකොනහොමද කියා විස්තර කරනවා නම් : ඉන්යටර්ඵයෙස්, තමන්ව use කරන members ලාට බල කරනවා, එකම විදිහට use යවන methods හැම member ටම access කළ හැකි යලස implement කරන්න කියල! [An interface forces each component to expose specific public members which will be used in a similar way.] අපි තවත් සරල උදාහරණයක් නදස බලමු: (ගිය සතියේ සහ යේ සතියේ කියපු යද්වල් පහසුයවන් අවයබෝධ කර ගැනීමට) Defining an Interface: IMyVidusaraInterface using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { interface IMyVidusaraInterface { void MethodToImplement(); } } Using above Interface: InterfaceImplementer using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ForVidusara { class InterfaceImplementer { static void Main() { InterfaceImplementer iImp = new InterfaceImplementer(); iImp.MethodToImplement(); Console.ReadKey(); } public void MethodToImplement() { Console.WriteLine("MethodToImplement () called."); } } } OutPut: යේ උදාහරණය ඔබට Interface Inheritance එක ගැන අවයබෝධයේ ලබා යදවි : IParentVidusaraInterface using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VidusaraInterfaces { interface IParentVidusaraInterface { void ParentInterfaceMethod(); } } IParentVidusaraInterface using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VidusaraInterfaces { interface IMyVidusaraInterface : IParentVidusaraInterface { void MethodToImplement(); } } InterfaceImplementer using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VidusaraInterfaces { class InterfaceImplementer : IMyVidusaraInterface { static void Main() { InterfaceImplementer iImp = new InterfaceImplementer(); iImp.MethodToImplement(); iImp.ParentInterfaceMethod(); Console.ReadKey(); } //Implementing the method of IMyVidusaraInterface public void MethodToImplement() { Console.WriteLine("MethodToImplement () called.n"); } //Implementing the method of IParentVidusaraInterface public void ParentInterfaceMethod() { Console.WriteLine("ParentInterfaceMe thod() called.n"); } } } OutPut:
  • 27. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි INTERFACES (තව දුරටත්) පසුගිය සතියේ අපි කතා කය ේ Interfaces ඔයේ වැඩසටහනකට යයොදා ගන්යන් යකොයහොමද කියලයි..... යේ ලිපියයන් ද අපි Interfaces වල ප්රාායයිගික යයමමක් ගැන අවධානය යයොමු කරමු. යකොයහොමද අපි C# වල IList නමැති Interface එක(one of the default interfaces provided by C#) අයේ වැඩසටහනකට යයොදාගන්යන් කියලා....ඒ සඳහා අපි List Operations (List නමැති Data Structure එක ගැන ඔබ දන්නවනේ යමය යේරුේ ගැනීම පහසු යවයි, යකයසේ යවතේ Data Structures & Algorithms ගැන මම යවනම ලිපි යප ක්, යේ ලිපි යප අවසන් වූ පසු ඔබ යවත යගන එන්නේ. Interfaces ගැන තරමක් ප්රායයිගික අවයබිධයක් ලබාමමටයි මම යේ වැඩසටහන ඔබ යවත යගන එන්යන්. (යේ වැඩසටහයන් ඉතිරිය ලබන සතියේ ප යවයි) Note: IList extends, IComparable and IEnumerable. using System; using System.Collections; namespace VidusaraList { class SimpleList : IList { private object[] contents = new object[10]; private int count; public SimpleList() { count = 0; } /* Implementing IList Members (Add, Clear, Contains, IndexOf, Insert and so on....)*/ public int Add(object value) { if (count < contents.Length) { contents[count] = value; count++; return (count - 1); } else { return -1; } } public void Clear() { count = 0; } public bool Contains(object value) { bool inList = false; for (int i = 0; i < Count; i++) { if (contents[i] == value) { inList = true; break; } } return inList; } public int IndexOf(object value) { int itemIndex = -1; for (int i = 0; i < Count; i++) { if (contents[i] == value) { itemIndex = i; break; } } return itemIndex; } public void Insert(int index, object value) { if ((count + 1 <= contents.Length) && (index < Count) && (index >= 0)) { count++; for (int i = Count - 1; i > index; i--) { contents[i] = contents[i - 1]; } contents[index] = value; } } public bool IsFixedSize { get { return true; } } public bool IsReadOnly { get { return false; } } public void Remove(object value) { RemoveAt(IndexOf(value)); } public void RemoveAt(int index) { if ((index >= 0) && (index < Count)) { for (int i = index; i < Count - 1; i++) { contents[i] = contents[i + 1]; } count--; } } public object this[int index] { get { return contents[index]; } set { contents[index] = value; } } //Implementing ICollection Members public void CopyTo(Array array, int index) { int j = index; for (int i = 0; i < Count; i++) { array.SetValue(contents[i], j); j++; } } public int Count { get { return count; } } public bool IsSynchronized { get { return false; } } // Return the current instance since the underlying store is not // publicly available. public object SyncRoot { get { return this; } } //Implementing IEnumerable Members public IEnumerator GetEnumerator() { // Refer to the IEnumerator documentation for an example of // implementing an enumerator. throw new Exception("The method or operation is not implemented."); } public void PrintContents() { Console.WriteLine("List has a capacity of {0} and currently has {1} elements.", contents.Length, count); Console.Write("List contents:"); for (int i = 0; i < Count; i++) { Console.Write(" {0}", contents[i]); } Console.WriteLine(); } } } යමයට අදා Program.cs එක ලබන සතියේ ඉදිරිපේ කරන්නේ. ඉහත class එයකන් කරන්යන් list එකකට elements, add කිරීම, display, delete කිරීම වැනි මූලික යේවල්ය. (ඔබ යහොඳින් එය අධsනය කරන්න) Expected Outcome: (Main program will give this output – it will be published next week)
  • 28. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි INTERFACES (තව දුරටත්) Continuing from last week: පසුගිය සතියේ ඉදිරිපත් කළ SimpleList නෝiග්රෑයම් එ ටකට ාළ main නෝiග්රෑයම් එ ටක: using System; using System.Text; namespace VidusaraList { class Program { static void Main(string[] args) { SimpleList test = new SimpleList(); // Populate the List Console.WriteLine("Current Members of the List:"); Console.WriteLine("------- ---------------------"); test.Add("Tharindu"); test.Add("Kamal"); test.Add("Sunil"); test.Add("Rajendra"); test.Add("Indika"); test.Add("Pavithra"); test.Add("Mahinda"); test.Add("Ranil"); test.PrintContents(); Console.WriteLine(); // Remove elements from the list Console.WriteLine("Remove elements from the List:"); Console.WriteLine("----- -------------------------"); test.Remove("Ranil"); test.Remove("Tharindu"); test.PrintContents(); Console.WriteLine(); // Add an element to the end of the list Console.WriteLine("Add an element to the end of the List:"); Console.WriteLine("----- ---------------------------------- "); test.Add("Sarath"); test.PrintContents(); Console.WriteLine(); // Insert an element into the middle of the list Console.WriteLine("Insert an element into the middle of the List:"); Console.WriteLine("------- -------------------------------------- "); test.Insert(4, "Karunamuny"); test.PrintContents(); Console.WriteLine(); // Check for specific elements in the list Console.WriteLine("Check for specific elements in the List:"); Console.WriteLine("-------- --------------------------------"); Console.WriteLine("List contains "Mahinda": {0}", test.Contains("Mahinda")); Console.WriteLine("List contains "Tharindu": {0}", test.Contains("Tharindu")); Console.ReadKey(); } } } Output: (යෙය පසුගිය සතියය ෙෙ ඉදිරිපත් කළා) ය ොඳයි, ඒ අපි බැලුයේ, IList නෙැති C# සතු in-built interface එක යයොදායෙන basic list operations කරන ආකාරයයි...... යේවයේ, INTERFACES වල ප්රාායයිගික වාත අපට ඉයෙන ෙ ැකියි... දැන් අපි බලමු INTERFACE එකක් ස ABSTRACT CLASS එකක් අ ර ඇති යවනස් කෙ යෙොකද්ද කියල.... යවනස ක ා කරන්න කලින්, ඔබ දන්නා පරිදි, යේ යදයකහි ඇති සොන කෙ යෙොකද්ද? නම් එ නළනකේම instances සැදිය න ොහැකි වීම INTERFACE vs ABSTRACT CLASS Note:  INTERFACE එකකින් derive වුනු class එකක INTERFACE එයක් ඇති සියලුෙ methods implement කළ යුතුය.  ABSTRACT CLASS එකකින් derive වුනු class එකක abstract class එයක් ඇති සියලුෙ abstract methods override කළයුතු වුව ද ABSTRACT CLASS එක තුළ abstract යනොවන methods තිබිය ැකි නිසා (implemented) inheritance තුළින් ඒ method එක derive වුනු class එකට ලැයබන බව අපි දනිමු. උදා රණ යදකක් ෙගින් අපි යේවා යත්රුේ ෙනිමු: public abstract class PassengerVehicle { public void Start() { Console.WriteLine("The vehicle has been started"); } public abstract void Drive(); public abstract void Park(); public abstract void ChangeGear(int gear); public void SwitchOff() { Console.WriteLine("The vehicle has been switched off"); } } --------------------------------------------------------------- public class Van: PassengerVehicle { public Van() { } public override void Drive() { Console.WriteLine("The van is being driven"); } public override void Park() { Console.WriteLine("The van is being parked"); } public override void ChangeGear(int gear) { Console.WriteLine("The van changed gear changed to " + gear.ToString()); } } public interface IVehicle { void Start(); void Drive(); void Park(); } --------------------------------------------------------------- public class Vehicle : IVehicle { public void Start() { Console.WriteLine("The vehicle has been started"); } public void Drive() { Console.WriteLine("The vehicle is being driven"); } public void Park() { Console.WriteLine("The vehicle is being parked"); } } නම් එ OOP ප ඩම් එ ම ල ව ගැ ඔනේ ාළහස් ාපට කියේ !
  • 29. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි SEALED CLASSES & METHODS අද ලිපියෙන් අපි කතා කරන්යන් Sealed Class ගැනයි. ඔබට class එකක් base class එකක් කරන්න අවශ්‍ය නැත්නම්, එහි ඇති methods override කිරීයම් අවශ්‍යතාවක් නැති නම් class එකක් seal කළ හැකියි.  Sealed Class:  Prevents the class from being sub- classed, means a sealed class cannot be a base class  Violates the whole object oriented notion of inheritance Why would we ever use a class as sealed? If and only if we need an absolute guarantee that none of the methods in that class will ever be overridden! C# වල යබොයහොමෙක් in-built classes sealed යලසයි පවතින්යන්. යහේතුව ඒවා extend කිරීමට අවසර නැති නිසා....(E.g. String class) If the String class is not a sealed class, then the .Net cannot guarantee how a String object would work on any given system. Example Sealed Class: using System; sealed class MyClass { public int a; public int b; } class MainClass { public static void Main() { MyClass mC = new MyClass(); mC.a = 110; mC.b = 150; Console.WriteLine("a = {0}, b = {1}", mC.a, mC.b); } } Another example: using System; class MainClass { static void Main(string[] args) { MySealedClass sealedCls = new MySealedClass(); int total = sealedCls.Add(4, 5); Console.WriteLine("Total = " + total.ToString()); } } // Sealed class sealed class MySealedClass { public int Add(int x, int y) { return x + y; } }  Sealed Method:  Prevents the method from being overridden in a sub class If a method declaration includes a sealed modifier, then that method is a sealed method. If you use the sealed modifier, then it must also include the override modifier. Use of the sealed modifier (use of a sealed class) prevents a derived class from further overriding the method in a sub class. Example for sealed methods: using System; class A { public virtual void methodA1() { Console.WriteLine("A.methodA1"); } public virtual void methodA2() { Console.WriteLine("A.methodA2"); } } class B: A { sealed override public void methodA1 () { Console.WriteLine("B.methodA1"); } override public void methodA2() { Console.WriteLine("B.methodA2"); } } class C: B { override public void methodA2() { Console.WriteLine("C.methodA2"); } }
  • 30. OOP සරලව.... පරිගණක ඉංජිනේරු, තරිඳු වීරසංහ විසනි Note: පසුගිය සතිනේ පළවුනේ 26 වන ලිපියයි. මුද්රiණ නෂ යයිනේ යය 24 නලස පළවී තිබුණි. අෂ අපි කතා කරේනේ Immutable Objects ගැනයි. Immutable Objects  කිසිඳු operation එකකට instance එකක instance variables වෙනස් කළ වනොහැකිය.  Any operation that causes such a change must instead return a new object with appropriately adjusted instance variables  Instance variables set කළ යුත්වත් object එකක් මුලින්ම හදපු වෙලවෙදියි.....  Strings are immutable objects උ.දා. Immutable object is an object whose state cannot be modified after it is created! වමයින් මා ඔබට සරලෙ වෙන ආ, OOP ලිපි වෙළ අෙසන් වෙනො.... OOP හි සාරාාංශයක් ෙහත දැක්වෙනො: Term Definition Abstract Data Type A user-defined data type, including both attributes (its state) and methods (its behaviour). An object oriented language will include means to define new types (see class) and create instances of those classes (see object). It will also provide a number of primitive types. Aggregation Objects that are made up of other objects are known as aggregations. The relationship is generally of one of two types:  Composition – the object is composed of other objects. This form of aggregation is a form of code reuse. E.g. A Car is composed of Wheels, a Chassis and an Engine  Collection – the object contains other objects. E.g. a List contains several Items; A Set several Members. Attribute A characteristic of an object. Collectively the attributes of an object describe its state. E.g. a Car may have attributes of Speed, Direction, Registration Number and Driver. Class The definition of objects of the same abstract data type. In Java class is the keyword used to define new types. Dynamic (Late) Binding The identification at run time of which version of a method is being called (see polymorphism). When the class of an object cannot be identified at compile time, it is impossible to use static binding to identify the correct object method, so dynamic binding must be used. Encapsulation The combining together of attributes (data) and methods (behaviour/processes) into a single abstract data type with a public interface and a private implementation. This allows the implementation to be altered without affecting the interface. Inheritance The derivation of one class from another so that the attributes and methods of one class are part of the definition of another class. The first class is often referred to the base or parent class. The child is often referred to as a derived or sub- class. Derived classes are always ‘a kind of’ their base classes. Derived classes generally add to the attributes and/or behaviour of the base class. Inheritance is one form of object-oriented code reuse. E.g. Both Motorbikes and Cars are kinds of MotorVehicles and therefore share some common attributes and behaviour but may add their own that are unique to that particular type. Interface The behaviour that a class exposes to the outside world; its public face. Also called its ‘contract’. In Java interface is also a keyword similar to class. However a Java interface contains no implementation: it simply describes the behaviour expected of a particular type of object, it doesn’t so how that behaviour should be implemented. Member Variable See attribute Method The implementation of some behaviour of an object. Message The invoking of a method of an object. In an object-oriented application objects send each other messages (i.e. execute each others methods) to achieve the desired behaviour. Object An instance of a class. Objects have state, identity and behaviour. Overloading Allowing the same method name to be used for more than one implementation. The different versions of the method vary according to their parameter lists. If this can be determined at compile time then static binding is used, otherwise dynamic binding is used to select the correct method as runtime. Polymorphism Generally, the ability of different classes of object to respond to the same message in different, class-specific ways. Polymorphic methods are used which have one name but different implementations for different classes. E.g. Both the Plane and Car types might be able to respond to a turnLeft message. While the behaviour is the same, the means of achieving it are specific to each type. Static(Early) Binding The identification at compile time of which version of a polymorphic method is being called. In order to do this the compiler must identify the class of an object. වේ ලුහුඬු කිරීම සඳහා මා අන්තර්ජාලවේ සහය ලබාෙත්තා. (Reference: www.ldodds.com/lectures/intro2java/OOP_Terms.doc ) OOP ලිපි වෙළ වමවලස අෙසන් කරනො.... අපි වෙනත් ලිපි වෙලකින් යලිත් ලබන සතිවේ සිට හමුවෙමු: