Você está na página 1de 26

Key Concepts of Object Orientation

Abstraction
Encapsulation
Polymorphism
Inheritance.
Abstraction is the ability to generalize an object as a data type that has a specific set of
characteristics and is able to perform a set of actions.
Object-oriented languages proide abstraction ia classes. Classes define the properties and
methods of an object type.
E!amples"
#ou can create an abstraction of a dog $ith characteristics% such as color% height% and
$eight% and actions such as run and bite. &he characteristics are called properties% and the
actions are called methods.
A 'ecordset object is an abstract representation of a set of data.
Classes are blueprints for Object.
Objects are instance of classes.
C( E!ample of Class")use a person class as e!ample*
public class +ra$
,
-- Class code.
.
Object References(defer for ref and value type discussion)
/hen $e $or0 $ith an object $e are using a reference to that object. On the other hand% $hen
$e are $or0ing $ith simple data types such as Integer% $e are $or0ing $ith the actual alue
rather than a reference.
/hen $e create a ne$ object using the 1e$ 0ey$ord% $e store a reference to that object in a
ariable. 2or instance"
+ra$ 3y+ra$ 4 ne$ +ra$5
&his code creates a ne$ instance of +ra$. /e gain access to this ne$ object ia the 3y+ra$
ariable. &his ariable holds a reference to the object.
l
1o$ $e hae a second ariable% $hich also has a reference to that same object. /e can use
either ariable interchangeably% since they both reference the e!act same object. &he thing $e
need to remember is that the ariable $e hae is not the object itself but% rather% is just a
reference or pointer to the object itself.
Access Modifiers
Access 3odifiers are 0ey$ords used to specify the declared accessibility of a member of a type.
Public is isible to eeryone. A public member can be accessed using an instance of a class% by a
class6s internal code% and by any descendants of a class.
Private is hidden and usable only by the class itself. 1o code using a class instance can access a
priate member directly and neither can a descendant class.
Protected members are similar to priate ones in that they are accessible only by the containing
class. 7o$eer% protected members also may be used by a descendant class. 8o members that are
li0ely to be needed by a descendant class should be mar0ed protected.

Internal/Friend is public to the entire application but priate to any outside applications.
2
Internal is useful $hen you $ant to allo$ a class to be used by other applications but resere
special functionality for the application that contains the class. Internal is used by C( and 2riend
by 9: .1E&.

Protected Internal may be accessed only by a descendant class that6s contained in the same
application as its base class. #ou use protected internal in situations $here you $ant to deny
access to parts of a class functionality to any descendant classes found in other applications.
Composition of an O!"C#
/e use an interface to get access to an object6s data and behaior. &he object6s data and
behaiors are contained $ithin the object% so a client application can treat the object li0e a blac0
bo! accessible only through its interface. &his is a 0ey object-oriented concept called
"ncapsulation. &he idea is that any programs that ma0e use of this object $on6t hae
direct access to the behaiors or data-but rather those programs must ma0e use of our object6s
interface.
3
&here are three main parts of Object"
;. Interface
<. Implementation or :ehaior
=. 3ember or Instance ariables
Interface
&he interface is defined as a set of methods )8ub and 2unction routines*% properties )Property
routines*% eents% and fields )ariables or arttributes* that are declared Public in scope.
Implementation or e$avior
&he code inside of a method is called the implementation. 8ometimes it is also called behaior
since it is this code that actually ma0es the object do useful $or0.
Client applications can use our object een if $e change the implementation-as long as $e don6t
change the interface. As long as our method name and its parameter list and return data type
remain unchanged% $e can change the implementation all $e $ant.
8o Met$od %i&nature depends on"
3ethod name
+ata types of parameters
Either Parameter is passed :y9al or :y'ef.
'eturn type of method.
Member or Instance 'ariables
&he third 0ey part of an object is its data% or state. Eery instance of a class is absolutely identical
in terms of its interface and its implementation-the only thing that can ary at all is the data
contained $ithin that particular object.
3ember ariables are those declared so that they are aailable to all code $ithin our class.
&ypically member ariables are Priate in scope-aailable only to the code in our class itself.
&hey are also sometimes referred to as instance ariables or as attributes. &he .1E& 2rame$or0
also refers to them as fields.
/e shouldn6t confuse instance ariables $ith properties( A Property is a type of method that is
geared around retrieing and setting alues% $hile an instance ariable is a ariable $ithin the
class that may hold the alue e!posed by a Property.
Interface loo)s li)e a class* but $as no implementation.
&he only thing it contains is definitions of eents% inde!ers% methods and-or properties. &he
reason interfaces only proide definitions is because they are inherited by classes and structs%
$hich must proide an implementation for each interface member defined. 8o% $hat are
4
interfaces good for if they don6t implement functionality> &hey6re great for putting together plug-
n-play li0e architectures $here components can be interchanged at $ill. 8ince all
interchangeable components implement the same interface% they can be used $ithout any e!tra
programming. &he interface forces each component to e!pose specific public members that $ill
be used in a certain $ay.
:ecause interfaces must be defined by inheriting classes and structs% they define a contract. 2or
instance% if class foo inherits from the I+isposable interface% it is ma0ing a statement that it
guarantees it has the +ispose)* method% $hich is the only member of the I+isposable interface.
Any code that $ishes to use class foo may chec0 to see if class foo inherits I+isposable. /hen
the ans$er is true% then the code 0no$s that it can call foo.+ispose)*.
+efining an Interface" 3yInterface.c
interface I3yInterface
,
oid 3ethod&oImplement)*5
.
Aboe listing sho$s defines an interface named I3yInterface. A common naming conention is
to prefi! all interface names $ith a capital ?I?% but this is not mandatory. &his interface has a
single method named 3ethod&oImplement)*. &his could hae been any type of method
declaration $ith different parameters and return types. 1otice that this method does not hae an
implementation )instructions bet$een curly braces- ,.*% but instead ends $ith a semi-colon% ?5?.
&his is because the interface only specifies the signature of methods that an inheriting class or
struct must implement.
All the methods of Interface are public by default and no access modifiers )li0e priate% public*
are allo$ed $ith any method of Interface.
@sing an Interface" InterfaceImplementer.cs
class InterfaceImplementer " I3yInterface
,
public oid 3ethod&oImplement)*
,
Console./riteAine)?3ethod&oImplement)* called.?*5
.
.
&he InterfaceImplementer class in aboe listing implements the I3yInterface interface.
Indicating that a class inherits an interface is the same as inheriting a class. In this case% the
follo$ing synta! is used"
class InterfaceImplementer " I3yInterface
5
1ote that this class inherits the I3yInterface interface5 it must implement its all members. /hile
implementing interface methods all those needs to be declared public only. It does this by
implementing the 3ethod&oImplement)* method. 1otice that this method implementation has
the e!act same signature% parameters and method name% as defined in the I3yInterface interface.
Any difference $ill cause a compiler error. Interfaces may also inherit other interfaces.
2ollo$ing listing sho$s ho$ inherited interfaces are implemented.
Interface Inheritance" InterfaceInheritance.cs
using 8ystem5
interface IParentInterface
,
oid ParentInterface3ethod)*5
.
interface I3yInterface " IParentInterface
,
oid 3ethod&oImplement)*5
.
class InterfaceImplementer " I3yInterface
,
public oid 3ethod&oImplement)*
,
Console./riteAine)?3ethod&oImplement)* called.?*5
.
public oid ParentInterface3ethod)*
,
Console./riteAine)?ParentInterface3ethod)* called.?*5
.
.
&he code in aboe listing contains t$o interfaces" I3yInterface and the interface it inherits%
IParentInterface. /hen one interface inherits another% any implementing class or struct must
implement eery interface member in the entire inheritance chain. 8ince the
InterfaceImplementer class in aboe listing inherits from I3yInterface% it also inherits
IParentInterface. &herefore% the InterfaceImplementer class must implement the
3ethod&oImplement)* method specified in the I3yInterface interface and the
ParentInterface3ethod)* method specified in the IParentInterface interface.
In summary% you can implement an interface and use it in a class. Interfaces may also be
inherited by other interface. Any class or struct that inherits an interface must also implement all
members in the entire interface inheritance chain.
In$eritance is the idea that one class% called a subclass% can be based on another class%
called a base class. Inheritance proides a mechanism for creating hierarchies of objects.
Inheritance is the ability to apply another class6s interface and code to your o$n class.
6
1ormal base classes may be instantiated themseles% or inherited. +eried classes can inherit
base class members mar0ed $ith protected or greater access. &he deried class is specialized to
proide more functionality% in addition to $hat its base class proides. Inheriting base class
members in deried class is not mandatory.
Access +ey,ords
base -B Access the members of the base class.
this -B 'efer to the current object for $hich a method is called.
&he base 0ey$ord is used to access members of the base class from $ithin a deried class"
Call a method on the base class that has been oerridden by another method. 8pecify $hich base-
class constructor should be called $hen creating instances of the deried class. A base class
access is permitted only in a constructor% an instance method% or an instance property accessor.
In follo$ing e!ample% both the base class% Person% and the deried class% Employee% hae a
method named Cetinfo. :y using the base 0ey$ord% it is possible to call the Cetinfo method on
the base class% from $ithin the deried class.
-- Accessing base class members
using 8ystem5
public class Person
,
protected string ssn 4 ?DDD-EE-FFFF?5
protected string name 4 ?Gohn A. 3algraine?5
public irtual oid CetInfo)*
,
Console./riteAine)?1ame" ,H.?% name*5
Console./riteAine)?881" ,H.?% ssn*5
.
.
class Employee" Person
,
public string id 4 ?A:CEFIE2C?5
public oerride oid CetInfo)*
,
-- Calling the base class CetInfo method"
base.CetInfo)*5
Console./riteAine)?Employee I+" ,H.?% id*5
.
.
class &estClass
,
public static oid 3ain)*
,
7
Employee E 4 ne$ Employee)*5
E.CetInfo)*5
.
.
Output
1ame" Gohn A. 3algraine
881" DDD-EE-FFFF
Employee I+" A:CEFIE2C
:ase class constructors can be called from deried classes. &o call a base class constructor% use
the base)* constructor reference. &his is desirable $hen it6s necessary to initialize a base class
appropriately.
7ere6s an e!ample that sho$s the deried class constructor $ith an address parameter"
abstract public class Contact
,
priate string address5
public Contact)string bJaddress*
,
this.address 4 bJaddress5
.
.
public class Customer " Contact
,
public Customer)string cJaddress* " base)CJaddress*
,
.
.
In this code% the Customer class does not hae an address% so it passes the parameter to its base
class constructor by adding a colon and the base 0ey$ord $ith the parameter to its declaration.
&his calls the Contact constructor $ith the address parameter% $here the address field in Contact
is initialized.
One more e!ample $hich sho$s ho$ base-class constructor is called $hen creating instances of
a deried class"
using 8ystem5
public class 3y:ase
,
int num5
public 3y:ase)*
,
Console./riteAine)?In 3y:ase)*?*5
8
.
public 3y:ase)int i*
,
num 4 i5
Console./riteAine)?in 3y:ase)int i*?*5
.
public int Cet1um)*
,
return num5
.
.
public class 3y+eried " 3y:ase
,
static int i 4 =<5
-- &his constructor $ill call 3y:ase.3y:ase)*
public 3y+eried)int ii* " base)*
,
.
-- &his constructor $ill call 3y:ase.3y:ase)int i*
public 3y+eried)* " base)i*
,
.
public static oid 3ain)*
,
3y+eried md 4 ne$ 3y+eried)*5 -- calls public 3y+eried)* " base)i* and
-- passes i4=< in base class
3y+eried md; 4 ne$ 3y+eried);*5 -- call public 3y+eried)* " base)i*
.
.
Output
in 3y:ase)int i*
in 3y:ase)*
&he follo$ing e!ample $ill not compile. It illustrates the effects of not including a default
constructor in a class definition"
abstract public class Contact
,
priate string address5
public Contact)string address*
,
this.address 4 address5
.
.
public class Customer " Contact
9
,
public Customer)string address*
,
.
.
In this e!ample% the Customer constructor does not call the base class constructor. &his is
obiously a bug% since the address field $ill neer be initialized.
/hen a class has no e!plicit constructor% the system assigns a default constructor. &he default
constructor automatically calls a default or parameterless base constructor. 7ere6s an e!ample of
automatic default constructor generation that $ould occur for the preceding e!ample"
public Customer)* " Contact)*
,
.
/hen a class does not declare any constructors% the code in this e!ample is automatically
generated. &he default base class constructor is called implicitly $hen no deried class
constructors are defined. Once a deried class constructor is defined% $hether or not it has
parameters% a default constructor $ill not be automatically defined% as the preceding code
sho$ed.
Callin& ase Class Members
+eried classes can access the members of their base class if those members hae protected or
greater access. 8imply use the member name in the appropriate conte!t% just as if that member
$ere a part of the deried class itself. 7ere6s an e!ample"
abstract public class Contact
,
priate string address5
priate string city5
priate string state5
priate string zip5
public string 2ullAddress)*
,
string fullAddress 4 address K 6Ln6 K city K 6%6 K state K 6 6 K zip5
return fullAddress5
.
.
public class Customer " Contact
,
public string Cenerate'eport)*
,
string fullAddress 4 2ullAddress)*5
l0
-- do some other stuff...
return fullAddress5
.
.
In aboe e!ample% the Cenerate'eport)* method of the Customer class calls the 2ullAddress)*
method in its base class% Contact. All classes hae full access to their o$n members $ithout
Mualification. Nualification refers to using a class name $ith the dot operator to access a class
member-3yObject.8ome3ethod)*% for instance. &his sho$s that a deried class can access its
base class members in the same manner as its o$n.
3ore &ips regarding Inheritance"
A static member cannot be mar0ed as oerride% irtual% or abstract. 8o follo$ing is an
error"
public static irtual oid Cet881)*
#ou can6t call static methods of base class from deried class using base 0ey$ord.
In aboe e!ample if you declare a static method as follo$s"
public class Person
,
protected string ssn 4 ?DDD-EE-FFFF?5
protected string name 4 ?Gohn A. 3algraine?5
public static oid CetInfo)*
,
-- Implementation
.
.
no$ you can6t call this method using base.CetInfo)* from deried class instead you hae to call
Person.CetInfo)* from deried class.
Inside 8tatic members $e can access only static fields% methods etc.
2ollo$ing e!ample $ill gie error% because $e can6t access name in CetInfo)* because name is
not static.
public class Person
,
protected string ssn 4 ?DDD-EE-FFFF?5
protected string name 4 ?Gohn A. 3algraine?5
public static oid CetInfo)*
,
Console./riteAine)?1ame" ,H.?% name*5
Console./riteAine)?881" ,H.?% ssn*5
.
.
ll
9irtual or abstract members cannot be priate.
If you are not oerriding a irtual method of base class in deried class% you can6t use
base class method by using base 0ey$ord in deried class. Also $hen you $ill create an
instance of deried class% it $ill call deried class method and you $ill only be able to
access base class method $hen you $ill create instance of base class.
#ou can6t decrease access leel of a method in deried class $hen you are oerriding a
base class method in deried class% ice ersa is possible.
3eans you can ma0e protected method of base class to public in deried class.
&he ?this? 0ey$ord refers to"
the current instance for $hich a method is called. 8tatic member functions do not hae a
this pointer. &he this 0ey$ord can be used to access members from $ithin constructors%
instance methods% and instance accessors.
&he follo$ing are common uses of this"
&o Mualify members hidden by similar names% for e!ample"
public Employee)string name% string alias*
,
this.name 4 name5
this.alias 4 alias5
.
In aboe e!ample% this.name refers to priate ariable name in the class. If $e $rite name 4
name% then this $ill refer to argument name of the constructor Employee and not to priate
ariable name in the class. In this case priate ariable name $ill neer be initialized.
&o pass an object as a parameter to other methods% for e!ample"
Calc&a!)this*5
&o declare inde!ers% for e!ample"
public int this Oint paramP
,
get
,
return arrayOparamP5
.
set
,
arrayOparamP 4 alue5
.
.
l2
It is an error to refer to this in a static method% static property accessor% or ariable initializer of a
field declaration.
In this e!ample% this is used to Mualify the Employee class members% name and alias% $hich are
hidden by similar names. It is also used to pass an object to the method Calc&a!% $hich belongs
to another class.
-- 0ey$ordsJthis.cs
-- this e!ample
using 8ystem5
public class Employee
,
public string name5
public string alias5
public decimal salary 4 =HHH.HHm5
-- Constructor"
public Employee)string name% string alias*
,
-- @se this to Mualify the fields% name and alias"
this.name 4 name5
this.alias 4 alias5
.
-- Printing method"
public oid printEmployee)*
,
Console./riteAine)?1ame" ,H.LnAlias" ,;.?% name% alias*5
-- Passing the object to the Calc&a! method by using this"
Console./riteAine)?&a!es" ,H"C.?% &a!.Calc&a!)this**5
.
.
public class &a!
,
public static decimal Calc&a!)Employee E*
,
return )H.HQmR)E.salary**5
.
.
public class 3ainClass
,
public static oid 3ain)*
,
-- Create objects"
Employee E; 4 ne$ Employee )?Gohn 3. &rainer?% ?jtrainer?*5
-- +isplay results"
E;.printEmployee)*5
l3
.
.
Output
1ame" Gohn 3. &rainer
Alias" jtrainer
&a!es" S<DH.HH
Abstract Classes
Abstract classes are a special type of base classes. In addition to normal class members% they
hae abstract class members. &hese Abstract class members are methods and properties that are
declared $ithout an implementation. All classes deried directly from abstract classes must
implement all of these abstract methods and properties.
Abstract classes can neer be instantiated. &his $ould be illogical% because of the members
$ithout implementations.8o $hat good is a class that can6t be instantiated> AotsT Abstract classes
sit to$ard the top of a class hierarchy. &hey establish structure and meaning to code. &hey ma0e
frame$or0s easier to build. &his is possible because abstract classes hae information and
behaior common to all deried classes in a frame$or0. &a0e a loo0 at the follo$ing e!ample"
abstract public class Contact -- Abstract Class Contact.
,
protected string name5
public Contact)*
,
-- statements...
.
public abstract oid generate'eport)*5
abstract public string 1ame
,
get5
set5
.
.
Contact% is an abstract class. Contact has t$o abstract members% and it has an abstract method
named generate'eport)*. &his method is declared $ith the abstract modifier in front of the
method declaration. It has no implementation )no braces* and is terminated $ith a semicolon.
&he 1ame property is also declared abstract. &he accessors of properties are terminated $ith
semicolons.
public class Customer " Contact -- Customer Inherits Abstract Class Contact.
,
string gender5
decimal income5
l4
int numberOf9isits5
public Customer)*
,
-- statements
.
public oerride oid generate'eport)*
,
-- uniMue report
.
public oerride string 1ame
,
get
,
numberOf9isitsKK5
return name5
.
set
,
name 4 alue5
numberOf9isits 4 H5
.
.
.
public class 8iteO$ner " Contact
,
int site7its5
string my8ite5
public 8iteO$ner)*
,
-- statements
.
public oerride oid generate'eport)*
,
-- uniMue report
.
public oerride string 1ame
,
get
,
site7itsKK5
return name5
.
set
,
name 4 alue5
site7its 4 H5
l5
.
.
.
&he abstract base class Contact has t$o deried classes% Customer and 8iteO$ner. :oth of these
deried classes implement the abstract members of the Contact class. &he generate'eport)*
method in each deried class has an oerride modifier in its declaration. Ai0e$ise% the 1ame
declaration contains an oerride modifier in both Customer and 8iteO$ner.
C( reMuires e!plicit declaration of intent $hen oerriding methods. &his feature promotes safe
code by aoiding the accidental oerriding of base class methods% $hich is $hat actually does
happen in other languages. Aeaing out the oerride modifier generates an error. 8imilarly%
adding a ne$ modifier also generates an error. Abstract methods must be oerridden and cannot
be hidden% $hich the ne$ modifier or the lac0 of a modifier $ould be trying to do.
&he most famous of all abstract classes is the Object class. It may be referred to as object or
Object% but it6s still the same class. Object is the base class for all other classes in C(. It6s also the
default base class $hen a base class is not specified. &he follo$ing class declarations produce
the same e!act results"
abstract public class Contact " Object
,
-- class members
.
abstract public class Contact
,
-- class members
.
Object is implicitly included as a base class if it is not already declared. :esides proiding the
abstract glue to hold together the C( class frame$or0% object includes built-in functionality%
some of $hich is useful for deried classes to implement.
-ifference bet,een Interface and Abstract Class
Interfaces are closely related to abstract classes that hae all members abstract.
2or an abstract class% at least one method of the class must be an abstract method that
means it may hae concrete methods.
2or an interface% all the methods must be abstract
Class that implements an interface much proide concrete implementation of all the
methods definition in an interface or else must be declare an abstract class
In C(% multiple inheritance is possible only through implementation of multiple
interfaces. Abstract class can only be deried once.
l6
An interface defines a contract and can only contains four entities iz methods%
properties% eents and inde!es. An interface thus cannot contain constants% fields%
operators% constructors% destructors% static constructors% or types.
Also an interface cannot contain static members of any 0ind. &he modifiers abstract%
public% protected% internal% priate% irtual% oerride is disallo$ed% as they ma0e no sense
in this conte!t.
Class members that implement the interface members must be publicly accessible.
Overridin& %ummary. (discuss also overload)
A deried class may oerride a irtual method of the base class $ith the 0ey$ord oerride. &he
follo$ing restrictions must be follo$ed.
Key$ord oerride is used in the definition of child class method that is going to oerride
the base class6s irtual method.
&he return type must be the same as the irtual method hae in base class.
&he name of the method should also be same.
&he parameter-list must also be same in order% number and type of parameters.
&he accessibility of the oerriding method should not be more restricted than that of the
accessibility defined $ith irtual method of the base class. &his accessibility either be the
same or less restricted.
&he irtual methods can be sealed in the child or deried classes to preent further
modifications in the implementation of the irtual method in the deried classes% by
declaring them as sealed methods.
/idin& ase Class Members
8ometimes deried class members hae the same name as a corresponding base class member. In
this case% the deried member is said to be ?hiding? the base class member.
/hen hiding occurs% the deried member is mas0ing the functionality of the base class member.
@sers of the deried class $on6t be able to see the hidden member5 they6ll see only the deried
class member. &he follo$ing code sho$s ho$ hiding a base class member $or0s.
abstract public class Contact
,
priate string address5
priate string city5
priate string state5
priate string zip5
public string 2ullAddress)*
l7
,
string fullAddress 4address K 6Ln6 Kcity K 6%6 K state K 6 6 K zip5
return fullAddress5
.
.
public class 8iteO$ner " Contact
,
public string 2ullAddress)*
,
string fullAddress5
-- create an address...
return fullAddress5
.
.
In this e!ample% both 8iteO$ner and its base class% Contact% hae a method named 2ullAddress)*.
&he 2ullAddress)* method in the 8iteO$ner class hides the 2ullAddress)* method in the Contact
class. &his means that $hen an instance of a 8iteO$ner class is ino0ed $ith a call to the
2ullAddress)* method% it is the 8iteO$ner class 2ullAddress)* method that is called% not the
2ullAddress)* method of the Contact class.
Although a base class member may be hidden% the deried class can still access it. It does this
through the base identifier. 8ometimes this is desirable. It is often useful to ta0e adantage of the
base class functionality and then add to it $ith the deried class code. &he ne!t e!ample sho$s
ho$ to refer to a base class method from the deried class.
abstract public class Contact
,
priate string address5
priate string city5
priate string state5
priate string zip5
public string 2ullAddress)*
,
string fullAddress 4address K 6Ln6 Kcity K 6%6 K state K 6 6 K zip5
return fullAddress5
.
.
public class 8iteO$ner " Contact
,
public string 2ullAddress)*
,
string fullAddress 4 base.2ullAddress)*5
-- do some other stuff...
return fullAddress5
.
l8
.
In this particular e!ample% the 2ullAddress)* method of the Contact class is called from $ithin
the 2ullAddress)* method of the 8iteO$ner class. &his is accomplished $ith a base class
reference. &his proides another $ay to reuse code and add on to it $ith customized behaior.
%ealed Classes
8ealed classes are classes that can6t be deried from. &o preent other classes from inheriting
from a class% ma0e it a sealed class. &here are a couple good reasons to create sealed classes%
including optimization and security.
8ealing a class aoids the system oerhead associated $ith irtual methods. &his allo$s the
compiler to perform certain optimizations that are other$ise unaailable $ith normal classes.
Another good reason to seal a class is for security. Inheritance% by its ery nature% dictates a
certain amount of protected access to the internals of a potential base class. 8ealing a class does
a$ay $ith the possibility of corruption by deried classes. A good e!ample of a sealed class is
the 8tring class. &he follo$ing e!ample sho$s ho$ to create a sealed class"
public sealed class Customer8tats
,
string gender5
decimal income5
int numberOf9isits5
public Customer8tats)*
,
.
.
public class CustomerInfo " Customer8tats -- error
,
.
&his e!ample generates a compiler error. 8ince the Customer8tats class is sealed% it can6t be
inherited by the CustomerInfo class.&he Customer8tats class $as meant to be used as an
encapsulated object in another class. &his is sho$n by the declaration of a Customer8tats object
in the Customer class.
public class Customer
,
Customer8tats my8tats5 -- o0ay
.
Polymorp$ism
l9
Polymorphism is reflected in the ability to $rite one routine that can operate on objects from
more than one class-treating different objects from different classes in e!actly the same $ay. 2or
instance% if both Customer and 9endor objects hae a 1ame property% and $e can $rite a routine
that calls the 1ame property regardless of $hether $e6re using a Customer or 9endor object%
then $e hae polymorphism.
A ehicle is a good e!ample of polymorphism. A ehicle interface $ould only hae those
properties and methods that all ehicles hae% a fe$ of $hich might include paint color% number
of doors% accelerator% and ignition. &hese properties and methods $ould apply to all types of
ehicles including cars% truc0s% and semi-truc0s.
Polymorphism $ill not implement code behind the ehicle6s properties and methods. Instead%
polymorphism is the implementation of an interface. If the car% truc0% and semitruc0 all
implement the same ehicle interface% then the client code for all three classes can be e!actly the
same.
C( gies us polymorphism through inheritance. C( proides a 0ey$ord irtual that is used in the
definition of a method to support polymorphism.
Child class are no$ free to proide their o$n implementation of this irtual method% that is
called oerriding. &he follo$ing points are important regarding irtual 0ey$ord"-
If the method is not irtual% the compiler simply uses the reference type to ino0e the appropriate
method.
If the method is irtual% the compiler $ill generate code to chec0up the reference type at runtime
it is actually denoting to% then the appropriate method is called from the class of the reference
type.
/hen a irtual method is called% runtime chec0 )late method binding* is made to identify the
object and appropriate method is ino0ed% all this is done at runtime.
In case of non-irtual methods% this information is aailable at compile time% so no runtime chec0
to identify the object is made% so slightly efficient in the $ay non-irtual methods are called. :ut
the behaior of irtual method is useful in many $ays5 the functionality they proide is fair
enough to bear this slight loss of performance.
Implementin& Polymorp$ism
&he 0ey factor here is the ability to dynamically ino0e methods in a class based on their type.
Essentially% a program $ould hae a group of objects% e!amine the type of each one% and e!ecute
the appropriate method. 7ere6s an e!ample"
using 8ystem5
public class /eb8ite
,
20
public string 8ite1ame5
public string @'A5
public string +escription5
public /eb8ite)*
,
.
public /eb8ite) string str8ite1ame% string str@'A% string str+escription *
,
8ite1ame 4 str8ite1ame5
@'A 4 str@'A5
+escription 4 str+escription5
.
public oerride string &o8tring)*
,
return 8ite1ame K ?% ? K@'A K ?% ? K+escription5
.
.
/hen $e inherit aboe class% $e hae t$o choices to ino0e constructor of the class. 8o this is
an e!ample of design time polymorphism. 7ere at design time $e hae to decide $hich method
$e need to ino0e $hile inheriting the class.
Polymorphism is the capability of a program to carry out dynamic operations by implementing
methods of multiple deried classes through a common base class reference. Another definition
of polymorphism is the ability to treat different objects the same $ay. &his means that the
runtime type of an object determines its behaior rather than the compile-time type of its
reference.
2l
1O&E8
+iscuss benefits of OOP
o Some Benefits of OOP
1. Through inheritance, we can eliminate redundant code and extend the use of
existing classes
3. We can build programs from the woring the modules that communicate with one
another, rather than ha!ing to start writing the code from scratch. "eusable code
#. The principle of data hiding$encapsulation% helps the programmer to build secure
programs that cannot be in!aded b& the code in other parts of the program.
'. (t is possible to ha!e multiple instances of an ob)ect to coexist without an&
interference.
*. (t is possible to map ob)ects in the problem domain to those in the
program $abstraction+generali,ation%. "epresent real word ob)ects inside code
-. (t is eas& to partition the wor in a pro)ect based on ob)ects.
.. Ob)ect oriented s&stems can be easil& upgraded from small to large s&stem. $easier
to maintain%
Cannot be learned in one s$eep% can be achieed thru practice and e!perience
Abstraction or Ceneralization U ability to generalize an object as a data type% $ith a
specific set of characteristics)atributes* and functions)methods or procedures*
Implemented using classes
Class is the blueprint or plan for an object
Object is the actual instance of the class
Class )plan for the house* - object )actual house that is built*
22
Cenralize -0ey $ord U design classes so that they can be re-used
E!ample non generalized class
DBCon

SaveToDataBase()
GetFromDatabase()
;. Inside each method there is a connection string
<. Inside each method the select or the insert statement is hardcoded along $ith any
parameters
=. /ill $or0 only for that specific application
E!ample generalized class
DBCon
- Constring
SaveToDataBase(string SQL,
parameters)
GetFromDataBase(string SQL,
parameters)
;. &his class can be reused
<. 1o specific connection string $e can assign the appropriate con string
$hen needed
=. 8Ml statements and parameters are not hardcoded
Access modifiers
Public U all
Priate U $ithin the class
Protected - $ithin the class also by the child class
Protected Internal - $ithin the class also by the child class% but $ith in same application
23
Composition of an object
interface= public members accesible by others, not all methods should be accesible.
key word is anything that is public in the class
behavior/implementation = code behind the method or function, logic used
we can chage the behavior of an interface , as long as we dont change the
signiture, then the application wil still work.
signiture - 3ethod name
+ata types of parameters
Either Parameter is passed :y9al or :y'ef.
'eturn type of method.
member instance / variables = data or state
should be private, this variables are availble to all the code in the class
Encapsulation - &he idea is that any programs that ma0e use of this object $on6t hae
direct access to the behaiors or data-but rather those programs must ma0e use of our
object6s interface.
lnterface (type of class) if a class is a blueprint for an object, an interface can be
considered as a blueprint for a class, it defines which methods, properties it should at
least contain. Methods has no definition/ code only signiture. When we inherit an
interface we must include all methods that is contained in the interface, or the program
will not compile. So we are forced to put the methods thaty are defiend in the interface,
parang contrata. (see page 5 for definitions).
Usually as a procatice interfaces has a capital "l" in the begining of the name.
Ex. ldisposable, lconnection... etc... in .NET all builtin interfaces uses this
convention.
Discuss example in page 5, ehre we have an iterface and how it is inherited. Using
colon sign after the class name
Discuss hte posibility of an iterface in heriting another interface, base interface
"lParentlnterface", then another inrface inherite this arent interface "I3yInterface", then
a class inherits ImyInterface% this class must no$ inplement both methods from Parent
interface and 3yinterface. )see page F*
In$eritance is the idea that one class% called a subclass% can be based on another class%
called a base class. Inheritance is the ability to apply another class6s interface and code to
your o$n class.
24
What can we get from the parent? Everthing that is marked public , protected
Ex: we have base class named "Animal", this has height and weight attribute, and also
run, eat and sleep method, whiach are all protected.. Then we create a DOG class which
inherits the animal class, the DOG clss now has all the atribute, and methods from
ANlMAL class, no need to define them.. it is directly accesible inside the DOG class.
lt is posible that both BASE and CHlLD class has methods or attributes which has the
same name. To specify which method or attribute to aacess we can use ACCESS
KEYWORDS
base -> Access the members of the base class.
this -> Refer to the current object for which a method is called.
(see page 7 to 8 for example)
Use virtual to make a method overidable, use overrride to overide a virtual method.
Abstarct Clases then have normal class members, they have abstract class members,
meaning mix of methods with and without implementation (sample on page l4) discuss
samples
Difference between Interface and Abstract Class
lnterfaces are closely related to abstract classes that have all members abstract.
For an abstract class, at least one method of the class must be an abstract method that
means it may have concrete methods.
For an interface, all the methods must be abstract
Class that implements an interface much provide concrete implementation of all the
methods definition in an interface or else must be declare an abstract class
ln C#, multiple inheritance is possible only through implementation of multiple interfaces.
Abstract class can only be derived once.
An interface defines a contract and can only contains four entities viz methods,
properties, events and indexes. An interface thus cannot contain constants, fields,
operators, constructors, destructors, static constructors, or types.
Also an interface cannot contain static members of any kind. The modifiers abstract,
public, protected, internal, private, virtual, override is disallowed, as they make no sense in
this context.
Class members that implement the interface members must be publicly accessible.

Hiding Base Class Members
Sometimes derived class members have the same name as a corresponding base class
member. ln this case, the derived member is said to be "hiding" the base class member.
Users of the derived class won't be able to see the hidden member; they'll see only the
derived class member. (discuss page l7)
%ealed Classes
25
8ealed classes are classes that can6t be deried from. &o preent other classes from inheriting
from a class% ma0e it a sealed class. &here are a couple good reasons to create sealed classes%
including optimization and security )page ;V sample*
Polymorp$ism
is reflected in the ability to $rite one routine that can operate on objects from more than
one class-treating different objects from different classes in e!actly the same $ay.
(see page 20)

26