Sie sind auf Seite 1von 16

Object Oriented Programming in C# 1

C# 30

C# 3.0
Chapter 8 Object Oriented
Programming in C#

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

Object Oriented Programming in C# 2

C# 30

Moving to OOP
In the next
ne t slides,
slides youll
o ll find an enhanced
p y class
version of the Employee
This version involves inheritance and polymorphism
to 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

Object Oriented Programming in C# 3

C# 30

The Employees System Example


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

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

Object Oriented Programming in C# 4

C# 30

The Employees Class


publicvirtualvoidCalculateSalary(){
if(_salary<_minimumSalary)
Salary=
Salary
_minimumSalary;
minimumSalary;
}
p
publicoverridestringToString(){
g
g() {
return"Employeename:"+_name;
}
publicint Salary
{
get;
protectedset;
}
}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Object Oriented Programming in C# 5

C# 30

The Programmer Class


publicclassProgrammer:Employee
{
privatebool _knowsCSharp;
privateint _bonus;
publicProgrammer(stringname,int
(
salary,bool knowsCSharp)
)
:base(name,salary){
_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

Object Oriented Programming in C# 6

C# 30

The Programmer Class


publicoverridevoidCalculateSalary()
{
if( bonus>0)
if(_bonus>0)
{
_sa
salary+=
a y
_bo
bonus;
us;
_bonus=0;
}
base.CalculateSalary();
}
}
}

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

Object Oriented Programming in C# 7

C# 30

The Project Manager Class


publicclassProjectManager
bli l
P j tM
:Employee
E l
{
privateint _numProjectsManaged;
numProjectsManaged;
privateProject_currentProject;
publicProjectManager(stringname,int salary,
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

Object Oriented Programming in C# 8

C# 30

The Project Manager Class


publicoverridevoidCalculateSalary()
{
switch(_currentProject.Status){
caseProject.ProjectStatus.BeforeSchedule:
_salary+=(int)(_salary*0.1);
break;
caseProject.ProjectStatus.OnSchedule:
caseProject ProjectStatus OnSchedule:
_salary+=(int)(_salary*0.05);
b ea ;
break;
}
base.CalculateSalary();
}
}

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

Object Oriented Programming in C# 9

C# 30

The Employees System Example


classEmployeeMain
{
staticvoidMain(string[]args){
ProjectManager mary =
newProjectManager("MaryWhite",10000,3);
Programmerjack=
newProgrammer("JackSmith",7000,true);
Payrollpayroll =newPayroll(100);
payroll.AddEmployee(mary);
pay o . dd p oyee(jac );
payroll.AddEmployee(jack);
payroll.PrintReport();

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

Object Oriented Programming in C# 10

C# 30

The Employees System Example


Projectproject1=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

Object Oriented Programming in C# 11

C# 30

Inheritance and Polymorphism


Follo
Following
ing OO principles,
principles inheritance is an
p
is a relationship:
A Programmer is an Employee

Inheritance is defined using the :


operator:
publicclassProgrammer: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

C# 30

Object Oriented Programming in C# 12

Inheritance and Polymorphism


The derived
deri ed 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 keyword
p
publicvirtualvoidCalculateSalary()
y()
{...}

Note that a virtual method cannot be private!

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

Object Oriented Programming in C# 13

C# 30

Inheritance and Polymorphism


To override a base method
method, a derived
class must add the override keyword
publicoverridevoidCalculateSalary()
{
//Addsbonusifprovided
base.CalculateSalary();
}

Overridden methods cannot change the virtual


methods accessibility level

Base class methods may be called from a


derived 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

Object Oriented Programming in C# 14

C# 30

Inheritance and Polymorphism


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:
Employeee=newProgrammer;

The ability of a base reference to refer to


an object of any of its derived classes is
th key
the
k to
t polymorphism
l
hi
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

C# 30

Object Oriented Programming in C# 15

Polymorphism Payroll Class


usingSystem;
i
publicclassPayroll
{
privateEmployee[]_employees;
privateint _numEmployees;
publicPayroll(int maxEmployees){
_employees=newEmployee[maxEmployees];
}
publicbool AddEmployee(Employeeemployee){
if(_numEmployees <_employees.Length){
_employees[_numEmployees++]=employee;
returntrue;
t
t
}
returnfalse;
}

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

C# 30

Object Oriented Programming in C# 16

Polymorphism Payroll Class


publicvoidCalculateSalaries(){
for(int i =0;i <_numEmployees;++i){
_employees[i].CalculateSalary();
employees[i].CalculateSalary();
}
}
publicvoidPrintReport(){
Console.WriteLine("Payrollreport:");
f
for(int
(i t i =0;i
i <_numEmployees;++i){
l
i) {
Employeeemp =_employees[i];
Console.WriteLine(emp
( p +"salary:"+emp.Salary);
y
p
y)
}
}
}

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

Object Oriented Programming in C# 17

C# 30

An Inheritance Related Riddle


What if a deri
derived
ed class defines a method
g
identical to a base virtual
with a signature
method but omits the override keyword?
Employee class CalculateSalary definition:
publicvirtualvoidCalculateSalary(){//}

Programmer class CalculateSalary definition:


publicvoidCalculateSalary(){// }
publicvoidCalculateSalary(){//}

Will this compile?

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

Object Oriented Programming in C# 18

C# 30

And the Answer Is


Is
Compiling the above
abo e sit
situation
ation will
ill ca
cause
se
the following
g warning:
g
'Programmer.CalculateSalary()'hidesinherited
p y
y()
member'Employee.CalculateSalary()'.
Tomakethecurrentmemberoverride
thatimplementation,addtheoverridekeyword.
Otherwiseaddthenewkeyword.
h
i
dd h
k
d

Activating
A ti ti this
thi method
th d through
th
h a base
b
class
l
reference
f
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

C# 30

Object Oriented Programming in C# 19

override vs.
vs new
A derived
deri ed class has two
t o override
o erride options:
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

C# 30

Object Oriented Programming in C# 20

virtual override and new


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

It p
prevents a common p
problem in C++
A programmer intending to override a method makes
a mistake in the signature,
g
, thus g
gets an overloaded
method instead of overridden method
In C# the compiler
can catch the signature
mistake
p
g
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Object Oriented Programming in C# 21

Abstract Methods and Classes


To define a p
pure
re virtual
irt al method use
se the
y
abstract keyword
An abstract method cannot be implemented
If a class has even one abstract method
method, it should
also be defined as abstract
A class deriving from an abstract class should either
implement its base abstract methods or be an
abstract class itself
It is impossible to create an instance of an abstract
class

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

C# 30

Object Oriented Programming in C# 22

Sealed Methods
It is possible to stop method o
overrideerride
y by
y defining
g an overrided method
ability
as a sealed one, using the sealed
keyword:
classDerived:Base
{
publicoverridesealed voidf1(){}
}

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

Object Oriented Programming in C# 23

C# 30

Sealed Classes
A more common usage of the sealed
keyword
y
is related to classes:
It is possible to prevent further derivation of a class,
by defining it as a sealed class
sealedclassPoint
{//}

When
Wh appropriate,
i
defining
d fi i a class
l
as
sealed is recommended, since it may
enable several optimizations
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Object Oriented Programming in C# 24

C# 30

Up Casts and Down Casts


Casting a derived
deri ed class into a base cast
performed implicitly
p
y
can be p
This type of cast is termed: up-cast

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:
We have a reference to an Employee object and we
want 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

C# 30

Object Oriented Programming in C# 25

Up Casts and Down Casts


As opposed to an up
up-cast,
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 onlyy be done


explicitly:
Employeee=...;
Employeee=
;
//ereferstoanexistingemployee
Programmerp=(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

C# 30

Object Oriented Programming in C# 26

The is Operator
Is a run-time
r n time type
t pe of an object compatible
type?
with a given
g
yp
The is operator is used in an expression of the form:
expression
is
i
i type
t
p
It will return true if expression
is not null and can be
cast to type
Employeee1=...;
Employeee1=
;
if(e1is Programmer)
{
Programmerp=(Programmer)e1;
p.Program();
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Object Oriented Programming in C# 27

C# 30

The as Operator
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
p
p
performs both the check
and the cast operations
The as operator is used in an expression of the form:
expression as type
Employeee1=...;
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# 28

C# 30

Chapter 8 Exercises 1 & 2

THE SHAPES EXERCISE

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

C# 30

Object Oriented Programming in C# 29

Calling Virtual Methods From


Base Constructor

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
class method version
Note that the derived class constructor was not executed yet
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

C# 30

Object Oriented Programming in C# 30

Overloading Base Methods in


Derived Class

In C++
Derived class methods hide base class methods by
name
If a derived class defines a method with an identical name as
of its base, calling the method through a derived object would
always map to the derived method version

In C#
Derived class methods hide base class methods by
signature
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
both
base and
dd
derived
i d method
th d versions
i
participate
ti i t as
candidates in the method call resolution
The best match between these two versions will be activated
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Object Oriented Programming in C# 31

C# 30

Chapter Summary
C# is a p
pure
re object oriented lang
language:
age
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

Das könnte Ihnen auch gefallen