key concepts of object orientation

Upload: kenneth-sy

Post on 03-Jun-2018

232 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/12/2019 Key Concepts of Object Orientation

    1/26

    Key Concepts of Object Orientation

    Abstraction

    Encapsulation

    Polymorphism

    Inheritance.

    Abstractionis the ability to generalize an object as adata type that has a specific set ofcharacteristics and is able to perform a set of actions.

    Object-oriented languages proide abstraction ia classes. Classes define the properties andmethods 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 theactions 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*

    publicclass+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 aluerather 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.

    1

    http://www.c-sharpcorner.com/UploadFile/tusharkantagarwal/objectorientedcsharp11162005070743AM/objectorientedcsharp.aspxhttp://www.c-sharpcorner.com/UploadFile/tusharkantagarwal/objectorientedcsharp11162005070743AM/objectorientedcsharp.aspxhttp://www.c-sharpcorner.com/UploadFile/tusharkantagarwal/objectorientedcsharp11162005070743AM/objectorientedcsharp.aspxhttp://www.c-sharpcorner.com/UploadFile/tusharkantagarwal/objectorientedcsharp11162005070743AM/objectorientedcsharp.aspx
  • 8/12/2019 Key Concepts of Object Orientation

    2/26

    1o$ $e hae a second ariable% $hich also has a reference to that same object. /e can useeither ariable interchangeably% since they both reference the e!act same object. &he thing $eneed to remember is that the ariable $e hae is not the object itself but% rather% is just areference 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.

    Publicis isible to eeryone. A public member can be accessed using an instance of a class% by aclass6s internal code% and by any descendants of a class.

    Privateis hidden and usable only by the class itself. 1o code using a class instance can access apriate member directly and neither can a descendant class.

    Protectedmembers are similar to priate ones in that they are accessible only by the containingclass. 7o$eer% protected members also may be used by a descendant class. 8o members that areli0ely 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

  • 8/12/2019 Key Concepts of Object Orientation

    3/26

    Internal is useful $hen you $ant to allo$ a class to be used by other applications but reserespecial functionality for the application that contains the class. Internal is used by C( and 2riendby 9: .1E&.

    Protected Internal may be accessed only by a descendant class that6s contained in the sameapplication as its base class. #ou use protected internal in situations $here you $ant to denyaccess 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 andbehaiors are contained $ithin the object% so a client application can treat the object li0e a blac0bo! 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 haedirect access to the behaiors or data-but rather those programs must ma0e use of our object6sinterface.

    3

  • 8/12/2019 Key Concepts of Object Orientation

    4/26

    &here are three main parts of Object"

    ;. Interface

  • 8/12/2019 Key Concepts of Object Orientation

    5/26

    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 allinterchangeable components implement the same interface% they can be used $ithout any e!traprogramming. &he interface forces each component to e!pose specific public members that $illbe used in a certain $ay.

    :ecause interfaces must be defined by inheriting classes and structs% they define a contract. 2orinstance% if class foo inherits from the I+isposable interface% it is ma0ing a statement that itguarantees 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. /henthe ans$er is true% then the code 0no$s that it can call foo.+ispose)*.

    +efining an Interface" 3yInterface.c

    interfaceI3yInterface,

    oid3ethod&oImplement)*5

    Aboe listing sho$s defines an interface named I3yInterface. A common naming conention isto prefi! all interface names $ith a capital ?I?% but this is not mandatory. &his interface has asingle method named 3ethod&oImplement)*. &his could hae been any type of methoddeclaration $ith different parameters and return types. 1otice that this method does not hae animplementation )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 orstruct 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

    classInterfaceImplementer " I3yInterface,publicoid3ethod&oImplement)*,Console./riteine)?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% thefollo$ing synta! is used"

    classInterfaceImplementer " I3yInterface

    5

  • 8/12/2019 Key Concepts of Object Orientation

    6/26

    1ote that this class inherits the I3yInterface interface5 it must implement its all members. /hileimplementing interface methods all those needs to be declared public only. It does this byimplementing the 3ethod&oImplement)* method. 1otice that this method implementation hasthe 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

    using8ystem5interfaceIParentInterface,oidParentInterface3ethod)*5interfaceI3yInterface " IParentInterface,

    oid3ethod&oImplement)*5classInterfaceImplementer " I3yInterface,publicoid3ethod&oImplement)*,Console./riteine)?3ethod&oImplement)* called.?*5publicoidParentInterface3ethod)*,Console./riteine)?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 mustimplement eery interface member in the entire inheritance chain. 8ince theInterfaceImplementer class in aboe listing inherits from I3yInterface% it also inheritsIParentInterface. &herefore% the InterfaceImplementer class must implement the3ethod&oImplement)* method specified in the I3yInterface interface and theParentInterface3ethod)* method specified in the IParentInterface interface.

    In summary% you can implement an interface and use it in a class. Interfaces may also beinherited by other interface. Any class or struct that inherits an interface must also implement allmembers in the entire interface inheritance chain.

    In$eritanceis 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

  • 8/12/2019 Key Concepts of Object Orientation

    7/26

    1ormal base classes may be instantiated themseles% or inherited. +eried classes can inheritbase class members mar0ed $ith protected or greater access. &he deried class is specialized toproide more functionality% in addition to $hat its base class proides. Inheriting base classmembers 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 classaccess 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 etinfo. :y using the base 0ey$ord% it is possible to call the etinfo method onthe base class% from $ithin the deried class.

    Accessing base class members

    using8ystem5publicclassPerson,protectedstringssn 4 ?DDD--FFFF?5protectedstringname 4 ?Gohn . 3algraine?5publicirtualoidetInfo)*

    ,Console./riteine)?1ame" ,H?% name*5Console./riteine)?881" ,H?% ssn*5classEmployee" Person,publicstringid 4 ?A:CFE2?5publicoerrideoidetInfo)*, Calling the base class etInfo method"base.etInfo)*5Console./riteine)?Employee I+" ,H?% id*5class&estClass,publicstaticoid3ain)*,

    7

  • 8/12/2019 Key Concepts of Object Orientation

    8/26

    Employee E 4 ne$Employee)*5E.etInfo)*5

    Output1ame" Gohn . 3algraine881" DDD--FFFFEmployee I+" A:CFE2

    :ase class constructors can be called from deried classes. &o call a base class constructor% usethe base)* constructor reference. &his is desirable $hen it6s necessary to initialize a base classappropriately.

    7ere6s an e!ample that sho$s the deried class constructor $ith an address parameter"

    abstractpublicclassContact,priatestringaddress5publicContact)stringbJaddress*,this.address 4 bJaddress5publicclassCustomer " Contact,publicCustomer)stringcJaddress* "base)CJaddress*

    ,

    In this code% the Customer class does not hae an address% so it passes the parameter to its baseclass 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 Contactis initialized.

    One more e!ample $hich sho$s ho$ base-class constructor is called $hen creating instances ofa deried class"

    using8ystem5publicclass3y:ase,intnum5public3y:ase)*,Console./riteine)?In 3y:ase)*?*5

    8

  • 8/12/2019 Key Concepts of Object Orientation

    9/26

    public3y:ase)inti*,num 4 i5Console./riteine)?in 3y:ase)int i*?*5

    publicintet1um)*,returnnum5publicclass3y+eried " 3y:ase,staticinti 4 =

  • 8/12/2019 Key Concepts of Object Orientation

    10/26

    ,publicCustomer)stringaddress*,

    In this e!ample% the Customer constructor does not call the base class constructor. &his isobiously 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 defaultconstructor automatically calls a default or parameterless base constructor. 7ere6s an e!ample ofautomatic default constructor generation that $ould occur for the preceding e!ample"

    publicCustomer)* " Contact)*,

    /hen a class does not declare any constructors% the code in this e!ample is automaticallygenerated. &he default base class constructor is called implicitly $hen no deried classconstructors are defined. Once a deried class constructor is defined% $hether or not it hasparameters% a default constructor $ill not be automatically defined% as the preceding codesho$ed.

    Callin& ase Class Members

    +eried classes can access the members of their base class if those members hae protected orgreater 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"

    abstractpublicclassContact,priatestringaddress5priatestringcity5priatestringstate5priatestringzip5publicstring2ullAddress)*,stringfullAddress 4 address 6Ln6 city 6%6 state 6 6 zip5returnfullAddress5publicclassCustomer " Contact,publicstringenerate'eport)*,stringfullAddress 4 2ullAddress)*5

    10

  • 8/12/2019 Key Concepts of Object Orientation

    11/26

    do some other stuff...returnfullAddress5

    In aboe e!ample% the enerate'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 $ithoutMualification. Nualification refers to using a class name $ith the dot operator to access a classmember-3yObject.8ome3ethod)*% for instance. &his sho$s that a deried class can access itsbase 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 et881)*

    #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"

    publicclassPerson,protectedstringssn 4 ?DDD--FFFF?5protectedstringname 4 ?Gohn . 3algraine?5publicstaticoidetInfo)*, Implementation

    no$ you can6t call this method using base.etInfo)* from deried class instead you hae to callPerson.etInfo)* 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 etInfo)* because name isnot static.

    publicclassPerson,

    protectedstringssn 4 ?DDD--FFFF?5protectedstringname 4 ?Gohn . 3algraine?5publicstaticoidetInfo)*,Console./riteine)?1ame" ,H?% name*5Console./riteine)?881" ,H?% ssn*5

    11

  • 8/12/2019 Key Concepts of Object Orientation

    12/26

  • 8/12/2019 Key Concepts of Object Orientation

    13/26

    It is an error to refer to this in a static method% static property accessor% or ariable initializer of afield 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 belongsto another class.

    0ey$ordsJthis.cs this e!ampleusing8ystem5publicclassEmployee,publicstringname5publicstringalias5publicdecimalsalary 4 =HHH.HHm5

    Constructor"publicEmployee)stringname% stringalias*, @se this to Mualify the fields% name and alias"this.name 4 name5this.alias 4 alias5 Printing method"publicoidprintEmployee)*,Console./riteine)?1ame" ,HLnAlias" ,;?% name% alias*5

    Passing the object to the Calc&a! method by using this"Console./riteine)?&a!es" ,H"C?% &a!.Calc&a!)this**5publicclass&a!,publicstaticdecimalCalc&a!)Employee E*,return)H.HQmR)E.salary**5publicclass3ainClass,publicstaticoid3ain)*, Create objects"Employee E; 4 ne$Employee )?Gohn 3. &rainer?% ?jtrainer?*5 +isplay results"E;.printEmployee)*5

    13

  • 8/12/2019 Key Concepts of Object Orientation

    14/26

    Output1ame" Gohn 3. &rainer

    Alias" jtrainer&a!es" S otsT Abstract classessit to$ard the top of a class hierarchy. &hey establish structure and meaning to code. &hey ma0eframe$or0s easier to build. &his is possible because abstract classes hae information andbehaior common to all deried classes in a frame$or0. &a0e a loo0 at the follo$ing e!ample"

    abstractpublicclassContact Abstract Class Contact.,protectedstringname5publicContact)*, statements...

    publicabstractoidgenerate'eport)*5abstractpublicstring1ame,get5set5

    Contact% is an abstract class. Contact has t$o abstract members% and it has an abstract methodnamed generate'eport)*. &his method is declared $ith the abstract modifier in front of themethod 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 $ithsemicolons.

    publicclassCustomer " Contact Customer Inherits Abstract Class Contact.,stringgender5decimalincome5

    14

  • 8/12/2019 Key Concepts of Object Orientation

    15/26

    intnumberOf9isits5publicCustomer)*, statements

    publicoerrideoidgenerate'eport)*, uniMue reportpublicoerridestring1ame,get,numberOf9isits5returnname5

    set,name 4 alue5numberOf9isits 4 H5publicclass8iteO$ner " Contact,intsite7its5stringmy8ite5public8iteO$ner)*, statementspublicoerrideoidgenerate'eport)*, uniMue reportpublicoerridestring1ame,get,site7its5returnname5set,name 4 alue5site7its 4 H5

    15

  • 8/12/2019 Key Concepts of Object Orientation

    16/26

    &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. i0e$ise% the 1amedeclaration contains an oerride modifier in both Customer and 8iteO$ner.

    C( reMuires e!plicit declaration of intent $hen oerriding methods. &his feature promotes safecode by aoiding the accidental oerriding of base class methods% $hich is $hat actually doeshappen in other languages. eaing out the oerride modifier generates an error. 8imilarly%adding a ne$ modifier also generates an error. Abstract methods must be oerridden and cannotbe 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 thedefault base class $hen a base class is not specified. &he follo$ing class declarations producethe same e!act results"

    abstractpublicclassContact " Object, class membersabstractpublicclassContact, class members

    Object is implicitly included as a base class if it is not already declared. :esides proiding theabstract 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.

    16

  • 8/12/2019 Key Concepts of Object Orientation

    17/26

    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 sensein 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. &hefollo$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 thesame 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% bydeclaring them as sealed methods.

    idin& ase Class Members

    8ometimes deried class members hae the same name as a corresponding base class member. Inthis 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 deriedclass member. &he follo$ing code sho$s ho$ hiding a base class member $or0s.

    abstractpublicclassContact,priatestringaddress5priatestringcity5priatestringstate5priatestringzip5publicstring2ullAddress)*

    17

  • 8/12/2019 Key Concepts of Object Orientation

    18/26

    ,stringfullAddress 4address 6Ln6 city 6%6 state 6 6 zip5returnfullAddress5

    publicclass8iteO$ner " Contact,publicstring2ullAddress)*,stringfullAddress5 create an address...returnfullAddress5

    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 Contactclass. &his means that $hen an instance of a 8iteO$ner class is ino0ed $ith a call to the2ullAddress)* method% it is the 8iteO$ner class 2ullAddress)* method that is called% not the2ullAddress)* method of the Contact class.

    Although a base class member may be hidden% the deried class can still access it. It does thisthrough the base identifier. 8ometimes this is desirable. It is often useful to ta0e adantage of thebase class functionality and then add to it $ith the deried class code. &he ne!t e!ample sho$sho$ to refer to a base class method from the deried class.

    abstractpublicclassContact

    ,priatestringaddress5priatestringcity5priatestringstate5priatestringzip5publicstring2ullAddress)*,stringfullAddress 4address 6Ln6 city 6%6 state 6 6 zip5returnfullAddress5publicclass8iteO$ner " Contact,publicstring2ullAddress)*,stringfullAddress 4base.2ullAddress)*5 do some other stuff...returnfullAddress5

    18

  • 8/12/2019 Key Concepts of Object Orientation

    19/26

    In this particular e!ample% the 2ullAddress)* method of the Contact class is called from $ithinthe 2ullAddress)* method of the 8iteO$ner class. &his is accomplished $ith a base classreference. &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 inheritingfrom 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 thecompiler 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 doesa$ay $ith the possibility of corruption by deried classes. A good e!ample of a sealed class isthe 8tring class. &he follo$ing e!ample sho$s ho$ to create a sealed class"

    publicsealedclassCustomer8tats,stringgender5decimalincome5intnumberOf9isits5publicCustomer8tats)*,

    publicclassCustomerInfo " Customer8tats error,

    &his e!ample generates a compiler error. 8ince the Customer8tats class is sealed% it can6t beinherited by the CustomerInfo class.&he Customer8tats class $as meant to be used as anencapsulated object in another class. &his is sho$n by the declaration of a Customer8tats objectin the Customer class.

    publicclassCustomer,Customer8tats my8tats5 o0ay

    Polymorp$ism

    19

  • 8/12/2019 Key Concepts of Object Orientation

    20/26

    Polymorphism is reflected in the ability to $rite one routine that can operate on objects frommore than one class-treating different objects from different classes in e!actly the same $ay. 2orinstance% if both Customer and 9endor objects hae a 1ame property% and $e can $rite a routinethat 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 thoseproperties and methods that all ehicles hae% a fe$ of $hich might include paint color% numberof doors% accelerator% and ignition. &hese properties and methods $ould apply to all types ofehicles 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 allimplement the same ehicle interface% then the client code for all three classes can be e!actly thesame.

    C( gies us polymorphism through inheritance. C( proides a 0ey$ord irtual that is used in thedefinition of a method to support polymorphism.

    Child class are no$ free to proide their o$n implementation of this irtual method% that iscalled 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 appropriatemethod.

    If the method is irtual% the compiler $ill generate code to chec0up the reference type at runtimeit 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 theobject 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 chec0to identify the object is made% so slightly efficient in the $ay non-irtual methods are called. :utthe behaior of irtual method is useful in many $ays5 the functionality they proide is fairenough 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!ecutethe appropriate method. 7ere6s an e!ample"

    using8ystem5publicclass/eb8ite,

    20

  • 8/12/2019 Key Concepts of Object Orientation

    21/26

  • 8/12/2019 Key Concepts of Object Orientation

    22/26

    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+generaliation%. "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 eneralization 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

  • 8/12/2019 Key Concepts of Object Orientation

    23/26

    enralize -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

  • 8/12/2019 Key Concepts of Object Orientation

    24/26

    Com%oston o& an ob'et

    nter&ae %*b+ members aesb+e b, oters$ not a++ meto.s so*+. be aesb+e/ e, or. s an,tn! tat s %*b+ n te +assbeavorm%+ementaton o.e ben. te meto. or &*nton$ +o! *se.

    e an a!e te beavor o& an nter&ae $ as +on! as e .ont an!e tes!nt*re$ ten te a%%+aton + st++ or/

    s!nt*re - 3ethod name

    +ata types of parameters

    Either Parameter is passed :y9al or :y'ef.

    'eturn type of method.

    member nstane varab+es .ata or stateso*+. be %rvate$ ts varab+es are ava+b+e to a++ te o.e n te +ass

    na%s*+aton - &he idea is that any programs that ma0e use of this object $on6t haedirect access to the behaiors or data-but rather those programs must ma0e use of ourobject6s interface.

    nter&ae (t,%e o& +ass) & a +ass s a b+*e%rnt &or an ob'et$ an nter&ae an be

    ons.ere. as a b+*e%rnt &or a +ass$ t .e&nes meto.s$ %ro%ertes t so*+. at

    +east ontan/ eto.s as no .e&nton o.e on+, s!nt*re/ en e nert an

    nter&ae e m*st n+*.e a++ meto.s tat s ontane. n te nter&ae$ or te %ro!ram

    ++ not om%+e/ So e are &ore. to %*t te meto.s tat, are .e&en. n te nter&ae$%aran! ontrata/ (see %a!e 5 &or .e&ntons)/

    s*a++, as a %roate nter&aes as a a%ta+ n te be!nn! o& te name/

    :/ .s%osab+e$ onneton/// et/// n /;T a++ b*+tn nter&aes *ses ts

    onventon/

    Ds*ss e:am%+e n %a!e 5$ ere e ave an ter&ae an. o t s nerte./ sn!

    o+on s!n a&ter te +ass name

    Ds*ss te %osb+t, o& an ter&ae n ertn! anoter nter&ae$ base nter&ae

  • 8/12/2019 Key Concepts of Object Orientation

    25/26

    at an e !et &rom te %arent= vertn! tat s mare. %*b+ $ %rotete.

    :> e ave base +ass name. ?nma+$ ts as e!t an. e!t attrb*te$ an. a+so

    r*n$ eat an. s+ee% meto.$ a are a++ %rotete.// Ten e reate a D@G +ass

    nerts te anma+ +ass$ te D@G +ss no as a++ te atrb*te$ an. meto.s &rom

    ?;?# +ass$ no nee. to .e&ne tem// t s .ret+, aesb+e ns.e te D@G +ass/

    t s %osb+e tat bot B?S an. CA#D +ass as meto.s or attrb*tes as te

    same name/ To s%e&, meto. or attrb*te to aaess e an *se ?CCSS@DS base -E ?ess te members o& te base +ass/

    ts -E e&er to te *rrent ob'et &or a meto. s a++e./(see %a!e 7 to 8 &or e:am%+e)

    se vrt*a+ to mae a meto. over.ab+e$ *se overrr.e to over.e a vrt*a+ meto./

    ?bstart C+ases ten ave norma+ +ass members$ te, ave abstrat +ass members$

    meann! m: o& meto.s t an. to*t m%+ementaton (sam%+e on %a!e 14) .s*sssam%+es

    Difference between Interface and Abstract Class nter&aes are +ose+, re+ate. to abstrat +asses tat ave a++ members abstrat/ For an abstrat +ass$ at +east one meto. o& te +ass m*st be an abstrat meto. tatmeans t ma, ave onrete meto.s/ For an nter&ae$ a++ te meto.s m*st be abstrat C+ass tat m%+ements an nter&ae m* %rov.e onrete m%+ementaton o& a++ temeto.s .e&nton n an nter&ae or e+se m*st be .e+are an abstrat +ass n CH$ m*+t%+e nertane s %ossb+e on+, tro*! m%+ementaton o& m*+t%+e nter&aes/?bstrat +ass an on+, be .erve. one/ ?n nter&ae .e&nes a ontrat an. an on+, ontans &o*r enttes vI meto.s$%ro%ertes$ events an. n.e:es/ ?n nter&ae t*s annot ontan onstants$ &e+.s$

    o%erators$ onstr*tors$ .estr*tors$ stat onstr*tors$ or t,%es/ ?+so an nter&ae annot ontan stat members o& an, n./ Te mo.&ers abstrat$%*b+$ %rotete.$ nterna+$ %rvate$ vrt*a+$ overr.e s .sa++oe.$ as te, mae no sense nts onte:t/ C+ass members tat m%+ement te nter&ae members m*st be %*b++, aessb+e/

    Hiding Base Class Members

    Sometmes .erve. +ass members ave te same name as a orres%on.n! base +assmember/ n ts ase$ te .erve. member s sa. to be J.n!J te base +ass member/

    sers o& te .erve. +ass onKt be ab+e to see te ..en memberL te,K++ see on+, te.erve. +ass member/ (.s*ss %a!e 17)

    %ealed Classes

    25

  • 8/12/2019 Key Concepts of Object Orientation

    26/26

    8ealed classes are classes that can6t be deried from. &o preent other classes from inheritingfrom 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 thanone class-treating different objects from different classes in e!actly the same $ay.(see %a!e 20)