480 likes | 833 Views
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.
E N D
Session 2: OOP in C# • OOP in C#: • Object Interaction. • Inheritance and Polymorphism. UCN Technology: Computer Science
Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle UCN Technology: Computer Science
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. UCN Technology: Computer Science
The Anatomy of a Class Classes are usually written by this pattern: classClassName { declaration of attributes constructors properties methods } UCN Technology: Computer Science
Remember this Exercise? • Create a VS project using this code:EmpProjectV1.rar • Test it – understand it. UCN Technology: Computer Science
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. UCN Technology: Computer Science
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. UCN Technology: Computer Science
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. UCN Technology: Computer Science
Example: • On Employee there is a method GiveBonus() which may have different implementations in the superclass and in the subclasses. UCN Technology: Computer Science
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. UCN Technology: Computer Science
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(); UCN Technology: Computer Science
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). UCN Technology: Computer Science
Polymorphism/Dynamic Binding Static type The way it used to be: Employee programmer = new Employee(“H. Acker","Programmer",22222); Static type = Dynamic type Static method call Dynamic type Statisc 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 UCN Technology: Computer Science
Example • Let’s look at the implementation of the model from earlier source Now: Employees at the cantina get double bonus. UCN Technology: Computer Science
Exercise • Banking2 UCN Technology: Computer Science
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 UCN Technology: Computer Science
public class Circle: Shape{ private int r; public override float Area(){ //--- } public override voidMoveTo(){ //-- } }//end circle What can we do with Area()? 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 What can we do to MoveTo()? UCN Technology: Computer Science
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.) UCN Technology: Computer Science
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 UCN Technology: Computer Science
Example/Exercise: German Student ExerciseGermanStudents.pdf UCN Technology: Computer Science
Example:Composite-pattern Composite: Graphical editor, Word processor, Inventories etc.. (What will a Show()-method look like on Shape, Circle, Picture etc.) View Code UCN Technology: Computer Science
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 UCN Technology: Computer Science
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 UCN Technology: Computer Science
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 Static type Dynamic type definesshow() UCN Technology: Computer Science
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.) UCN Technology: Computer Science
(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.) UCN Technology: Computer Science
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. UCN Technology: Computer Science
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 UCN Technology: Computer Science
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... } UCN Technology: Computer Science
More Examples • Organisational Structures (example) • Project Management (exercise) UCN Technology: Computer Science