30
Session 2: OOP in C# OOP in C#: Object Interaction. Inheritance and Polymorphism. FEN 2012 1 UCN Technology: Computer Science

Session 2: OOP in C#

  • Upload
    caia

  • View
    38

  • Download
    2

Embed Size (px)

DESCRIPTION

Session 2: OOP in C#. OOP in C#: Object Interaction. Inheritance and Polymorphism. Object-Oriented Programming. “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle. OO-Principles -encapsulation. - PowerPoint PPT Presentation

Citation preview

Page 1: Session 2: OOP in C#

Session 2: OOP in C#

• OOP in C#:– Object Interaction. – Inheritance and Polymorphism.

FEN 2012 1UCN Technology: Computer Science

Page 2: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 2

Object-Oriented Programming

“ The Three Pillars of OOP”:Encapsulation

InheritancePolymorphism

The Substitution Principle

Page 3: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 3

OO-Principles-encapsulation

• Seen from the outside an object is an entity offering a number of services (public methods and properties).

• The implementation and data representation are hidden or encapsulated. – This makes it possible to change implementation without

affecting other parts of the program.– Also it becomes possible to think, talk and use the object

without knowing the implementation.– Hiding data behind methods and properties are called

encapsulation or data abstraction. • Encapsulation or data abstraction is one the

fundamental principles of object-oriented programming.

Page 4: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 4

The Anatomy of a Class

Classes are usually written by this pattern:

class ClassName

{

declaration of attributes

constructors

properties

methods

}

Page 5: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 5

Remember this Exercise?

• Create a VS project using this code:EmpProjectV1.rar

• Test it – understand it.

Page 6: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 6

Inheritance in C#

• Every method and property is inherited – constructors are not.

• private members are inherited, but not directly accessible in the subclass.

• Every protected member of the base class is visible in subclasses, but hidden from other parts of the program.

• Members may be added in the subclass. • Multiple inheritance is not supported (by classes).• In C# every class inherits from Object.

Page 7: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 7

OO-Principles -inheritance

• Supports code-reuse.• Existing classes may be extended through

inheritance.• Inheritance is to used as type specialisation, that is:

we are modelling an “is-a” relationship between super- and subclass. For instance: CheckAccount is an Account, a special kind of account, but an account.

• So when we want to add specialised functionality to our system, inheritance may used by adding specialised classes.

• E.g.: CheckAccount may inherit Account.

Page 8: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 8

OO-Principles-inheritance

• Terminology: baseclass/superclass – subclass.

• Inheritance is to be used as specialisation/generalisation. Inheritance models an “is-a” relationship between super- and subclass.– A subclass is type compatible with the superclass:

CheckAccount c = new CheckAccount();

if (c is Account) -- yields true, if CheckAccount inherits Account

• The “is-a” relation is transitive.

Page 9: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 9

Example:

• On Employee there is a method GiveBonus() which may have different implementations in the superclass and in the subclasses.

Manager

noOfOpts

SalesPerson

sale

Employee

namesaleryposition

WorksOn

hours0..*1 0..*1

Project

namedepartment

10..* 10..*

Page 10: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 10

Inheritance- Constructors

• The base-part of a subclass is initialised by the call base(param-liste)

• This call is executed as the first step in executing the constructor of the subclass

• :base(param-liste) is placed immediately after the method-heading of the constructor (C++ syntax)

• If you don’t provide a default constructor (a constructor with no parameters) a default constructor is generated by the compiler. This will be called implicitly when an object of the subclass is created.

Page 11: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 11

Inheritance - redefining methods

• A method inherited from the base-class may be redefined (“overridden”) in the sub-class.

• For instance the Withdraw-method on Account/CheckAccout.

• In C# the must be specified “virtual” in the base-class and “override” in sub-class.

• The method in the sub-class has the same signature (name and parameter list) and the same return type as the method in the base-class.

• In the sub-class the redefined method in the base-class may be called using

base.methodName();

Page 12: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 12

Inheritance- polymorphism

• All reference variables in C# may refer to objects of subtypes.

• In the case of virtual methods it is first at execution time it is determined which method exactly is to be called.

• The method called is the one defined on the object that the reference currently is referring to.

• This is called dynamic binding – the call is bound to an actual code segment at runtime (dynamically).

Page 13: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 13

Polymorphism/Dynamic BindingThe way it used to be:

Employee programmer = new Employee(“H. Acker","Programmer",22222);

Static type = Dynamic type

Static method call

Static type

Dynamic type

Using polymorphism::

Employee boss = new Manager(”Big Boss",”CEO",52525, 500);

Dynamic type must be the same or a sub-type of the static type.

The compiler checks method-calls on the static type. Runtime the call is bonded to the dynamic type (dynamic binding).Dynamic binding requires methods to be specified virtual in the base-class and explicitly overridden in the sub-classes.

Dynamic type

Statisc type

Page 14: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science14

Example

• Let’s look at the implementation of the model from earlier

Manager

noOfOpts

SalesPerson

sale

Employee

namesaleryposition

WorksOn

hours0..*1 0..*1

Project

namedepartment

10..* 10..*

source

Now: Employees at the cantina get double bonus.

Page 15: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 15

Exercise

• Banking2

Page 16: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 16

Substitution Principle• Whenever inheritance is used; it should always be

possible to use objects of an sub-type (dynamic) instead of objects of the original (static) type.

• It should be possible to substitute objects of the subtype where objects of the base-type are expected.

• We can assure that this is meaningful by restricting the use of method-redefining by the following rule:

– If pre-conditions are changed, they are only weakened

– If post-conditions are changed, they are only strengthened

Page 17: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 17

Example:

public class Shape{ private int x,y; private Colour colour; //other attributtes public void MoveTo(int newX, int newY){ //PRE: 0 <= newX <= maxX && 0 <= newY <= maxY, // where maxX and maxY are the borders of the window // POST: x' = newX && y '= newY //suitable implementation } public virtual float Area(){ //PRE: none //POST: Area' = area of the shape with 4 decimals precision //implementation using some approximation }}//end Shape

public class Circle: Shape{

private int r;

public override float Area(){

//---

}

public override void MoveTo(){

//--

}

}//end circle

What can we do with Area()?

What can we do to MoveTo()?

Page 18: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 18

Inheritance - design considerations

• If we need a class to hold a list of employees, and it should be possible to add employees at the end of list, but nowhere else. Should we inherit Array or ArrayList or…?

• We are not to inherit at all!!! But use delegation.

• Inheritance is not to be used senselessly trying to reuse code! Inheritance is to be seen as sub typing!

• Inheritance models “is-a” relationships.

• Code-reuse is obtainable by using existing classes (composition, delegation etc.)

Page 19: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 19

Inheritance - abstract classes

• A class that defines one or more methods that are not implemented is called abstract. And the non-implemented methods are specified abstract.

• An abstract class can not be instantiated. It can only serve as base-class.

• An abstract class can only be used as static type, not dynamic type for object.

• Abstract methods must be implemented in the sub-classes. Otherwise the subclass itself becomes abstract.

• So an abstract method defines or specifies functionality (but does not implement) what must be implemented in the subclasses.

• Constructors in an abstract class are only used by the constructors in the subclasses

Page 20: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 20

Example/Exercise: German Student

ExerciseGermanStudents.pdf

Page 21: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 21

Example: Composite-pattern

1

Circle Rectangle Picture

Shape

0..*0..*

Position

1

Composite: Graphical editor, Word processor, Inventories etc..

(What will a Show()-method look like on Shape, Circle, Picture etc.)

View Code

Page 22: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 22

public abstract class Shape {private int id;private String color;private int xpos;private int ypos;

public void moveTo(Position newPos){ // PRE none // POST pos'=newPos }

public abstract void show();// PRE none

// POST figuren er tegnet

public abstract void hide(); // PRE none // POST figuren er skjult  public abstract float area();

// PRE none//POST Computes the area with 4 digits.

}//end Shape

Page 23: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 23

public class Circle: Shape{

private int r; //radius

public void show(){

//PRE none

//POST the circle is drawn

//Must be implemented using appropriate

//graphical routines

}

public void hide(){

//PRE none

//POST the circle is hidden

//Must be implemented using appropriate

//graphical routines

}

// More operations

}//end Circle

Page 24: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 24

public class Picture extends Shape{ ArrayList<Shape> pictList; // operationer til at tilføje og slette figurer mv. public void Show(){ //PRE none //POST The composite shape is drawn for(Shape s : pictList)

s.show(); }

} public float area() { float result=0; for(int i=0;i<pictList.size();i++) { result= result+pictList.get(i).area(); } return result;

}//end Picture

Dynamic type definesshow()

Static type

Page 25: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 25

Composite Pattern• The concept of patterns originates from architecture (Christopher

Alexander, 1977):

“Each pattern describes a problem which occurs over and over again in our environment, and then

describes the core of the solution to that problem, in such a way that you can use this solution a million

times over, without ever doing it the same way twice”

(Christopher Alexander e. a.: “A Pattern Language”. Oxford University Press, New York, 1977.)

Page 26: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 26

(OO) Design Patterns

• A well known and widely accepted concept in software engineering • Developed in the early 1990s and published by Gamma e.a.

(“Gang of Four”, GoF) in 1995:

“(…) design patterns (…) are descriptions of communicating objects and classes that are

customized to solve a general design problem in a particular context.”

(Erich Gamma e.a.:”Design Patterns. Elements of Reusable Object-Oriented Software”. Addison-Wesley. 1995.)

Page 27: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 27

The benefits of patterns

• A pattern captures a proven good design:– A pattern is based on experience– A pattern is discovered – not invented

• It introduces a new (and higher) level of abstraction, which makes it easier:– to talk and reason about design on a higher level– to document and communicate design

• One doesn’t have to reinvent solutions over and over again• Patterns facilitate reuse not only of code fragments, but of

ideas.

Page 28: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 28

Patterns as a learning tool

• It is often said that good skills in software construction require experience and talent

• …and neither can be taught or learned at school• Patterns capture experience (and talent) in a way that

is communicable and comprehensible• …and hence experience can be taught (and learned)• So one should put a lot of effort in studying patterns

Page 29: Session 2: OOP in C#

FEN 2012 UCN Technology: Computer Science 29

C#- When are objects equal?

• Classes ought to override the Equals-method inherited from Object

public class Customer{ . . .

public override bool Equals(object obj) { Customer other; if ((obj == null) || (!(obj is Customer))) return false; // surely not equal

other = (Customer) obj; // typecast to gain access return this.id == other.id; // equal, if ids are... }

Page 30: Session 2: OOP in C#

More Examples

• Organisational Structures (example)• Project Management (exercise)

FEN 2012 UCN Technology: Computer Science 30