Chapter 8 - Object Oriented Programming in C#

Embed Size (px)

DESCRIPTION

h

Citation preview

  • Object Oriented Programming in C# 1C# 30

    C# 3.0C# 3.0

    Chapter 8 Object Oriented Programming in C#Programming in C#

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Moving to OOPObject Oriented Programming in C# 2C# 30

    Moving to OOPIn the ne t slides o ll find an enhanced In the next slides, youll find an enhanced version of the Employee classp y This version involves inheritance and polymorphism

    to simulate a more complicated employees systemto simulate a more complicated employees system

    Read the program What seems to be similar to a C++ class definition? What seems to be different?

    List all your discoveries, understandings and questions

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • The Employees System ExampleObject Oriented Programming in C# 3C# 30

    The Employees System ExamplenamespaceAdvancedEmployeeManagementnamespaceAdvancedEmployeeManagement{

    publicclassEmployeepublicclassEmployee{

    privatestring name;p ate st g _ a e;protectedint _salary;privatestaticint _minimumSalary =6000;p _ y ;publicEmployee(stringname,int salary){

    _name=name;Salary=salary;

    }

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    The Employees ClassObject Oriented Programming in C# 4C# 30

    The Employees ClasspublicvirtualvoidCalculateSalary(){publicvirtualvoidCalculateSalary(){

    if(_salary

  • The Programmer ClassObject Oriented Programming in C# 5C# 30

    The Programmer ClasspublicclassProgrammer:EmployeepublicclassProgrammer:Employee{

    privatebool _knowsCSharp;privateint _bonus;

    ( )publicProgrammer(stringname,int salary,bool knowsCSharp):base(name,salary){

    knowsCSharp =knowsCSharp;_knowsCSharp =knowsCSharp;}

    publicint Bonus{set{_bonus=value;}}

    //Thisiswhatprogrammersaresupposedtodo:publicvoidProgram(){}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    The Programmer ClassObject Oriented Programming in C# 6C# 30

    The Programmer ClasspublicoverridevoidCalculateSalary()publicoverridevoidCalculateSalary(){

    if( bonus>0)if(_bonus>0){

    salary+= bonus;_sa a y _bo us;_bonus=0;

    }}base.CalculateSalary();

    }}

    }

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • The Project Manager ClassObject Oriented Programming in C# 7C# 30

    The Project Manager Classbli l P j tM E lpublicclassProjectManager :Employee

    {privateint numProjectsManaged;privateint _numProjectsManaged;privateProject_currentProject;

    publicProjectManager(stringname,int salary,int numProjectsManaged)int numProjectsManaged)

    :base(name,salary){numProjectsManaged =numProjectsManaged;_numProjectsManaged numProjectsManaged;

    }publicProjectProject {p j j {

    set{_currentProject =value;}}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    }

    The Project Manager ClassObject Oriented Programming in C# 8C# 30

    The Project Manager ClasspublicoverridevoidCalculateSalary()publicoverridevoidCalculateSalary(){

    switch(_currentProject.Status){caseProject.ProjectStatus.BeforeSchedule:

    _salary+=(int)(_salary*0.1);break;

    caseProject ProjectStatus OnSchedule:caseProject.ProjectStatus.OnSchedule:_salary+=(int)(_salary*0.05);break;b ea ;

    }base.CalculateSalary();

    }}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • The Employees System ExampleObject Oriented Programming in C# 9C# 30

    The Employees System Example classEmployeeMainclassEmployeeMain{

    staticvoidMain(string[]args){ProjectManager mary =

    newProjectManager("MaryWhite",10000,3);Programmerjack=

    newProgrammer("JackSmith",7000,true);Payrollpayroll =newPayroll(100);Payrollpayroll =newPayroll(100);payroll.AddEmployee(mary);payroll.AddEmployee(jack);pay o . dd p oyee(jac );

    payroll.PrintReport();

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    The Employees System ExampleObject Oriented Programming in C# 10C# 30

    The Employees System ExampleProjectproject1=newProject("Infrastructure");Projectproject1=newProject( Infrastructure );mary.Project =project1;

    project1.Status=Project.ProjectStatus.BeforeSchedule;

    jack.Bonus =500;

    payroll.CalculateSalaries();payroll.PrintReport();

    }}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Inheritance and PolymorphismObject Oriented Programming in C# 11C# 30

    Inheritance and PolymorphismFollo ing OO principles inheritance is an Following OO principles, inheritance is an is a relationship:p A Programmer is an Employee

    Inheritance is defined using the : Inheritance is defined using the :operator:

    Arguments are passed to the base classpublicclassProgrammer:Employee

    Arguments are passed to the base class constructor using the basekeyword:publicProgrammer(stringname,int salary,bool csharp)

    :base(name,salary){}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Inheritance and PolymorphismObject Oriented Programming in C# 12C# 30

    Inheritance and Polymorphism The deri ed class inherits base members The derived class inherits base members To express its specialization a derived class can

    either add new members, or override base member implementations

    To make a method override-able, a base class must use the virtual keywordclass must use the virtual keyword publicvirtualvoidCalculateSalary()

    Note that a virtual method cannot be private!

    p y(){...}

    Note that a virtual method cannot be private!

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Inheritance and PolymorphismObject Oriented Programming in C# 13C# 30

    Inheritance and Polymorphism To override a base method a derived To override a base method, a derived

    class must add the override keywordpublicoverridevoidCalculateSalary(){

    //Addsbonusifprovided//Addsbonusifprovidedbase.CalculateSalary();

    }

    Overridden methods cannot change the virtual methods accessibility level

    Base class methods may be called from a derived method using the base keywordderived method using the base keyword This can be used to share a common method

    implementation between all its derived classes

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    implementation between all its derived classes

    Inheritance and PolymorphismObject Oriented Programming in C# 14C# 30

    Inheritance and Polymorphism A base class reference variable can refer A base class reference variable can refer

    to an object of any of its derived classes Up cast: this assignment can be done with no explicit

    cast:

    The ability of a base reference to refer toEmployeee=newProgrammer;

    The ability of a base reference to refer to an object of any of its derived classes is th k t l hithe key to polymorphism Take a look at the following Payroll class, which

    handle all Employee types in a polymorphic way

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Polymorphism Payroll ClassObject Oriented Programming in C# 15C# 30

    Polymorphism Payroll ClassiusingSystem;

    publicclassPayroll{{privateEmployee[]_employees;privateint _numEmployees;publicPayroll(int maxEmployees){publicPayroll(int maxEmployees){

    _employees=newEmployee[maxEmployees];}publicbool AddEmployee(Employeeemployee){publicbool AddEmployee(Employeeemployee){

    if(_numEmployees

  • An Inheritance Related RiddleObject Oriented Programming in C# 17C# 30

    An Inheritance Related RiddleWhat if a deri ed class defines a method What if a derived class defines a method with a signature identical to a base virtual gmethod but omits the override keyword?

    Employee class CalculateSalary definition: Employee class CalculateSalary definition:publicvirtualvoidCalculateSalary(){//}

    Programmer class CalculateSalary definition:publicvoidCalculateSalary(){// }

    Will this compile?

    publicvoidCalculateSalary(){//}

    Will this compile?

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    And the Answer IsObject Oriented Programming in C# 18C# 30

    And the Answer IsCompiling the abo e sit ation ill ca se Compiling the above situation will cause the following warning: g g'Programmer.CalculateSalary()'hidesinheritedmember'Employee.CalculateSalary()'.p y y()Tomakethecurrentmemberoverridethatimplementation,addtheoverridekeyword.

    h i dd h k d

    A ti ti thi th d th h b l f

    Otherwiseaddthenewkeyword.

    Activating this method through a base class reference variable, the base class version will be activated

    ? Why? What does this new keyword mean?

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • override vs newObject Oriented Programming in C# 19C# 30

    override vs. newA deri ed class has t o o erride options A derived class has two override options: It can override the method, using the override

    keyword This will generate the derived method execution when

    activated through base reference variable

    A derived class can explicitly announce that its version of the method is a new one using the keyword new

    This will generate the base method execution when activated through a base reference variable

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    virtual override and newObject Oriented Programming in C# 20C# 30

    virtual,override and newThe enable precise e pression of the They enable precise expression of the method target:g Whether a method is an override-able Whether it overrides a previously defined method Whether it overrides a previously defined method Whether it is a new version of an already defined

    identical methodidentical method

    It prevents a common problem in C++p p A programmer intending to override a method makes

    a mistake in the signature, thus gets an overloaded g , gmethod instead of overridden method

    In C# the compiler can catch the signature mistake

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    p g

  • Abstract Methods and ClassesObject Oriented Programming in C# 21C# 30

    Abstract Methods and ClassesTo define a p re irt al method se the To define a pure virtual method use the abstract keywordy An abstract method cannot be implemented If a class has even one abstract method it should If a class has even one abstract method, it should

    also be defined as abstractA class deriving from an abstract class should either A class deriving from an abstract class should either implement its base abstract methods or be an abstract class itselfabstract class itself

    It is impossible to create an instance of an abstract classclass

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Sealed MethodsObject Oriented Programming in C# 22C# 30

    Sealed MethodsIt is possible to stop method o erride It is possible to stop method override-ability by defining an overrided method y y gas a sealed one, using the sealedkeyword:keyword:classDerived:BaseclassDerived:Base{

    publicoverridesealed voidf1(){}}}

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Sealed ClassesObject Oriented Programming in C# 23C# 30

    Sealed ClassesA more common usage of the sealed A more common usage of the sealedkeyword is related to classes:y It is possible to prevent further derivation of a class,

    by defining it as a sealed classby defining it as a sealed classsealedclassPoint{//}

    Wh i d fi i l

    {//}

    When appropriate, defining a class as sealed is recommended, since it maysealed is recommended, since it may enable several optimizations

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Up Casts and Down CastsObject Oriented Programming in C# 24C# 30

    Up Casts and Down CastsCasting a deri ed class into a base cast Casting a derived class into a base cast can be performed implicitlyp p y This type of cast is termed: up-cast

    What about the other direction? What about the other direction? Sometimes we have a base class reference, but we

    want to cast it into a derived class reference

    For example:For example: We have a reference to an Employee object and we

    want to cast it to a Programmer referencewant to cast it to a Programmer reference To be able to call a Programmer specific method: Program()

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Up Casts and Down CastsObject Oriented Programming in C# 25C# 30

    Up Casts and Down Casts As opposed to an up cast which is safe by As opposed to an up-cast, which is safe by

    definition, a down-cast might not be safe When a mistaken down-cast occurs at run-time, an InvalidCastException exception is thrown

    Therefore, a down-cast can only be done , yexplicitly:

    Employeee= ;Employeee=...;//ereferstoanexistingemployeeProgrammerp=(Programmer) e;

    The developer should be aware that this cast may cause an exception

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    cause an exception

    The is OperatorObject Oriented Programming in C# 26C# 30

    The is OperatorIs a r n time t pe of an object compatible Is a run-time type of an object compatible with a given type?g yp The is operator is used in an expression of the form:

    i i t

    It will return true if expression is not null and can be

    expression is type

    pcast to typeEmployeee1= ;Employeee1=...;if(e1is Programmer){

    Programmerp=(Programmer)e1;p.Program();

    }

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    }

  • The as OperatorObject Oriented Programming in C# 27C# 30

    The as Operator To safely cast down we need to To safely cast down we need to

    Check if an object implements a specified interface Cast it to a reference of the interface type

    The as operator performs both the check p pand the cast operations The as operator is used in an expression of the form: The as operator is used in an expression of the form:

    expression as type

    Employeee1=...;Programmerp=e1as Programmer;Programmerp=e1as Programmer;if(p!=null)

    p.Program();

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Object Oriented Programming in C# 28C# 30

    Chapter 8 Exercises 1 & 2

    THE SHAPES EXERCISE

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Calling Virtual Methods From Object Oriented Programming in C# 29C# 30

    Base ConstructorIn C++ In C++ Calling a virtual method from base class constructor

    results calling the base method version During base class constructor activation the objects virtual

    table pointer points to the base class virtual table

    In C# Calling a virtual method from base class constructor

    results calling to the derived class method versionresults calling to the derived class method version Note that the derived class constructor was not executed yet At this point the method is running with fields default value(!)At this point the method is running with fields default value(!)

    Be aware of this behavior change!

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

    Overloading Base Methods in Object Oriented Programming in C# 30C# 30

    Derived Class In C++ In C++

    Derived class methods hide base class methods by namename

    If a derived class defines a method with an identical name as of its base, calling the method through a derived object wouldof its base, calling the method through a derived object would always map to the derived method version

    In C#In C# Derived class methods hide base class methods by

    signaturesignature If a derive class defines a method with an identical name as

    of its base and the method is called through a derived object, b th b d d i d th d i ti i tboth base and derived method versions participate as candidates in the method call resolutionThe best match between these two versions will be activated

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

  • Chapter SummaryObject Oriented Programming in C# 31C# 30

    Chapter SummaryC# is a p re object oriented lang age C# is a pure object oriented language: Everything is derived from object There are many new keywords that support safe

    inheritance virtual override new abstract sealed is &as

    We can also define virtual & abstract properties

    Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel