Session 2: OOP in C# OOP in C#: –Object Interaction. –Inheritance and Polymorphism. Autumn 20121UCN Technology: IT/Computer Science.

Slides:



Advertisements
Similar presentations
Chapter 13 - Inheritance. Goals To learn about inheritance To learn about inheritance To understand how to inherit and override superclass methods To.
Advertisements

Inheritance in collections Week Main concepts to be covered Inheritance in ArrayList objects Subtyping Substitution.
CS1054: Lecture 18 - Inheritance. The DoME example "Database of Multimedia Entertainment" stores details about CDs and videos –CD: title, artist, # tracks,
Objects First With Java A Practical Introduction Using BlueJ Improving structure with inheritance 2.0.
Improving structure with inheritance Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts.
1 OOP in C#:Object Interaction. Inheritance and Polymorphism. Session 2: OOP in C#
Chapter 8 Improving Structure with Inheritance. The DoME Example The Database of Multimedia Entertainment We will be storing information about CDs and.
Session 07: C# OOP 4 Review of: Inheritance and Polymorphism. Static and dynamic type of an object. Abstract Classes. Interfaces. FEN AK - IT:
Improving structure with inheritance (Chapters 8 and 9)
Improving structure with inheritance
Improving structure with inheritance. 25/11/2004Lecture 7: Inheritance2 Main concepts to be covered Inheritance Subtyping Substitution Polymorphic variables.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance Chapter 8.
More about inheritance Exploring polymorphism. 02/12/2004Lecture 8: More about inheritance2 Main concepts to be covered method polymorphism static and.
Object Oriented Concepts in Java Objects Inheritance Encapsulation Polymorphism.
More about inheritance Exploring polymorphism 5.0.
More about inheritance Exploring polymorphism 3.0.
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
CC1007NI: Further Programming Week 2 Dhruba Sen Module Leader (Islington College)
Programming Languages and Paradigms Object-Oriented Programming.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
1 OOP in C#: Object Interaction. Inheritance and Polymorphism OOP in C# - Del 1.
Programming Fundamentals 2: Inheritance/ F II Objectives – –the use of super, overriding, method polymorphism (dynamic binding), protected.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
CS2110: SW Development Methods Inheritance in OO and in Java Part 1: Introduction Readings: A few pages in Ch. 2 of MSD text introduce this Section 3.3.
What is inheritance? It is the ability to create a new class from an existing class.
Lecture 8: Object-Oriented Design. 8-2 MicrosoftIntroducing CS using.NETJ# in Visual Studio.NET Objectives “Good object-oriented programming is really.
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Topic 4 Inheritance.
Object Oriented Software Development
Session 04: C# OOP 2 OOP in C#: Object-Oriented Design.
More about inheritance Exploring polymorphism 5.0.
Session 02 and 03: C# OOP 1 OOP in C#: Classes and Objects in C#. Object-Oriented Design. UML Class Diagram. Object Interaction. FEN AK IT:
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object-Oriented Programming Chapter Chapter
Object Oriented Programming
Objects First With Java A Practical Introduction Using BlueJ Method overriding 2.0.
Comp1004: Inheritance I Super and Sub-classes. Coming up Inheritance and Code Duplication – Super and sub-classes – Inheritance hierarchies Inheritance.
ISBN Object-Oriented Programming Chapter Chapter
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Improving structure with inheritance 3.0. The media project stores details about CDs and DVDs –CD: title, artist, number of tracks, playing time, got-it,
Session 06: C# OOP-3 Inheritance and Polymorphism. Static and dynamic type of an object. FEN AK - IT: Softwarekonstruktion.
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
OOP in C# - part 1 OOP in C#: –Object Interaction. –Inheritance and Polymorphism (next module). FEN 20121UCN Technology: Computer Science.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Inheritance and Polymorphism
More about inheritance
More about inheritance
COS 260 DAY 19 Tony Gauvin.
Lecture 19 - Inheritance (Contd).
Java Programming Language
More about inheritance
Comp1202: Inheritance I Super and Sub-classes.
F II 8. More on Inheritance Objectives
Improving structure with inheritance
Lecture 15 Inheritance.
Presentation transcript:

Session 2: OOP in C# OOP in C#: –Object Interaction. –Inheritance and Polymorphism. Autumn 20121UCN Technology: IT/Computer Science

Autumn 2012UCN Technology: IT/Computer Science2 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle

Autumn 2012UCN Technology: IT/Computer Science3 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.

Autumn 2012UCN Technology: IT/Computer Science4 The Anatomy of a Class Classes are usually written by this pattern: class ClassName { declaration of attributes constructors properties methods }

Autumn 2012UCN Technology: IT/Computer Science5 The Class BankAccount - attributes and constructor namespace Banking { public class BankAccount { private double balance; private int accNo; private int interestRate; public BankAccount(int no, int ir) { balance = 0; accNo = no; intrestRate = ir; }

Autumn 2012UCN Technology: IT/Computer Science6 Methods public bool Withdraw(double amount) public void Deposite(double amout) public void GiveInterest()

Autumn 2012UCN Technology: IT/Computer Science7 Properties public int InterestRate { get{return interestRate;} set{if( value>=0) interestRate = value;} }

Object Interaction Objects may be connected in different ways: –Association (“know-of-relation”). One object uses another. –Aggregation (“part-of-relation”). One object is a part of another. The distinction is not always clear. Autumn 2012UCN Technology: IT/Computer Science8 Means aggregation

Cardinality or Multiplicity Tells how many objects an object may be associated with: –One customer may have one account, an account must belong to a customer. (1 – 1) –One customer may have many accounts, an account must belong to one customer. (1 – n) –A customer may one or more accounts, an account may belong to one or more customers. (n – m) Autumn 2012UCN Technology: IT/Computer Science9 Goes for aggregation as well.

public class Customer{ //… private BankAccount account; //… account= new BankAccount(no, ir, bal); Autumn 2012UCN Technology: IT/Computer Science10 Customer is responsible for creating BankAccount objects. The association is implemented by an object reference (attribute). Implementing 1 - 1

Implementing 1 - n One customer may have many accounts, an account must belong to one customer. Possible solution: A collection of BankAccounts in Customer (accounts) Autumn 2012UCN Technology: IT/Computer Science11

In the Code public class Customer{ //… private List accounts; //… public Customer(int cNo, string n){ //… accounts = new List (); } public void AddAccount(BankAccount acc){ accounts.Add(acc); } //… Autumn 2012UCN Technology: IT/Computer Science12 View Source

Implementing n - m A customer may have one or more accounts, an account may belong to one or more customers. Possible solution: A collection of BankAccounts in Customer (accounts) and a collection of Customers (owners) in BankAccount. Autumn 2012UCN Technology: IT/Computer Science13

Example: Project Management An employee may work on several projects. A project may have several employees working on it. We need to record the number of hours a given employee has spent on a given project: Autumn 2012UCN Technology: IT/Computer Science14

Autumn 2012UCN Technology: IT/Computer Science15 Exercise: Re-cap and getting started Create a VS project using this code: EmpProjectV1.rar EmpProjectV1.rar Test it – understand it.

The DoME example (from Kölling and Barnes: “Objects First…”) "Database of Multimedia Entertainment" stores details about CDs and DVDs –CD: title, artist, # tracks, playing time, got-it, comment –DVD: title, director, playing time, got-it, comment allows (later) to search for information or print lists Autumn UCN Technology: IT/Computer Science

DoME objects Autumn UCN Technology: IT/Computer Science

DoME object model Autumn UCN Technology: IT/Computer Science

Class diagram View Source (dome-v1)dome-v1 Autumn UCN Technology: IT/Computer Science

Critique of DoME code duplication –CD and DVD classes very similar (large part are identical) –makes maintenance difficult/more work –introduces danger of bugs through incorrect maintenance code duplication also in Database class Autumn UCN Technology: IT/Computer Science

Using inheritance Autumn UCN Technology: IT/Computer Science

Using inheritance define one base or super class: Item define subclasses for DVD and CD the super class defines common attributes the subclasses inherit the super class attributes the subclasses add own attributes Autumn UCN Technology: IT/Computer Science

Inheritance in C# public class Item {... } public class CD : Item {... } public class DVD : Item {... } no change here change here View Source (dome-v2)dome-v2 Autumn UCN Technology: IT/Computer Science

Subtyping First, we had: public void AddCD( CD theCD) public void Add DVD ( DVD the DVD ) Now, we have: public void AddItem( Item theItem) We call this method with: DVD dvd = new DVD (...) ; myDB.AddItem(my DVD ); Static type Dynamic type Autumn UCN Technology: IT/Computer Science

Static and dynamic type The declared type of a variable is its static type. The type of the object a variable refers to is its dynamic type. The compiler’s job is to check for static-type violations. for(Item item : items) { item.Print(); // Item must have // declared a Print method. } Autumn UCN Technology: IT/Computer Science

Subclasses and subtyping Classes define types. Subclasses define subtypes. Objects of subclasses can be used where objects of supertypes are required. (This is called substitution.) Autumn UCN Technology: IT/Computer Science

Polymorphic variables Object variables in C# are polymorphic. (They can reference objects of more than one type.) They can reference objects of the declared type, or of subtypes of the declared type. Autumn UCN Technology: IT/Computer Science

Object diagram Static type Dynamic type Autumn UCN Technology: IT/Computer Science

Conflicting output CD: A Swingin' Affair (64 mins)* Frank Sinatra tracks: 16 my favourite Sinatra album DVD: O Brother, Where Art Thou? (106 mins) Joel & Ethan Coen The Coen brothers’ best movie! title: A Swingin' Affair (64 mins)* my favourite Sinatra album title: O Brother, Where Art Thou? (106 mins) The Coen brothers’ best movie! What we want What we have Autumn UCN Technology: IT/Computer Science

The inheritance hierarchy Here we only know information in Item Autumn UCN Technology: IT/Computer Science

Overriding: the solution print method in both super- and subclasses. Satisfies both static and dynamic type checking. View Source (dome-v3)dome-v3 Autumn UCN Technology: IT/Computer Science

Overriding Superclass and subclass define methods with the same signature. Each has access to the fields of its class. Superclass satisfies static type check. Subclass method is called at runtime – it overrides the superclass version. What becomes of the superclass version? Autumn UCN Technology: IT/Computer Science

Method lookup No inheritance or polymorphism. The obvious method is selected. Autumn UCN Technology: IT/Computer Science

Method lookup Inheritance but no overriding. The inheritance hierarchy is ascended, searching for a match. Autumn UCN Technology: IT/Computer Science

Method lookup Polymorphism and overriding. The ‘first’ version found (starting at the bottom of the hierarchy) is used. Autumn UCN Technology: IT/Computer Science

Method lookup summary The variable is accessed. The object stored in the variable is found. The class of the object is found. The class is searched for a method match. If no match is found, the superclass is searched. This is repeated until a match is found, or the class hierarchy is exhausted. Overriding methods take precedence. Autumn UCN Technology: IT/Computer Science

Call to base in methods Overridden methods are hidden but we often still want to be able to call them. An overridden method can be called from the method that overrides it. –base.Method(...) –Compare with the use of base in constructors. Autumn UCN Technology: IT/Computer Science

Defining and Calling an overridden method public class CD : Item {... public override void Print() { base.Print(); --- }... } public class Item {... public virtual void Print() { --- }... } Autumn UCN Technology: IT/Computer Science

Autumn 2012UCN Technology: IT/Computer Science39 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.

Autumn 2012UCN Technology: IT/Computer Science40 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.

Autumn 2012UCN Technology: IT/Computer Science41 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.

Autumn 2012UCN Technology: IT/Computer Science42 Example: On Employee there is a method GiveBonus() which may have different implementations in the superclass and in the subclasses.

Autumn 2012UCN Technology: IT/Computer Science43 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.

Autumn 2012UCN Technology: IT/Computer Science44 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();

Autumn 2012UCN Technology: IT/Computer Science45 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).

Autumn 2012UCN Technology: IT/Computer Science46 Polymorphism/Dynamic Binding The 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 Static type

Autumn 2012UCN Technology: IT/Computer Science 47 Example Let’s look at the implementation of the model from earlier source Now: Employees at the cantina get double bonus.

Autumn 2012UCN Technology: IT/Computer Science48 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.)

Autumn 2012UCN Technology: IT/Computer Science49 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

Interfaces An interface may be seen as a purely abstract class. –Interface: only method signatures, no implementation! (All methods are abstract) An interface represents a design. Example: –An interface to Employee: interface IEmployee { void GiveBonus(double amount); string Name { get; set; } double Salery { get; set; } string ToString(); } Autumn UCN Technology: IT/Computer Science

Why use interfaces? Formalise system design before implementation –especially useful with large systems. Contract-based programming –the interface represents the contract between client and object. Low coupling! –decouples specification and implementation. –facilitates reusable client code. –client code will work with both existing and future objects as long as the interface is not changed. Multiple inheritance –A class may implement several interfaces, but only inherit one class. (No competing implementations). Autumn UCN Technology: IT/Computer Science

Autumn 2012UCN Technology: IT/Computer Science52 Example/Exercise: German Student ExerciseGermanStudents.pdf

Autumn 2012UCN Technology: IT/Computer Science53 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... }