Object Oriented Software Development

Slides:



Advertisements
Similar presentations
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Advertisements

Solutions to Review Questions. 4.1 Define object, class and instance. The UML Glossary gives these definitions: Object: an instance of a class. Class:
Session 07: C# OOP 4 Review of: Inheritance and Polymorphism. Static and dynamic type of an object. Abstract Classes. Interfaces. FEN AK - IT:
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Object-oriented Programming Concepts
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Chapter 10 Classes Continued
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
Object Oriented Software Development
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.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Chapter 8 More Object Concepts
Object Oriented Concepts
CISC6795: Spring Object-Oriented Programming: Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Lecture 9 Polymorphism Richard Gesick.
OBJECT ORIENTED PROGRAMMING CONCEPTS ISC 560. Object-oriented Concepts  Objects – things names with nouns  Classes – classifications (groups) of similar.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
Object-Oriented Programming Chapter Chapter
M1G Introduction to Programming 2 5. Completing the program.
Object Oriented Programming
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Introduction to Object-Oriented Programming Lesson 2.
CS 106 Introduction to Computer Science I 04 / 18 / 2008 Instructor: Michael Eckmann.
Object Oriented Software Development 4. C# data types, objects and references.
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.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
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)
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
1 Inheritance One of the goals of object oriented programming is code reuse. Inheritance is one mechanism for accomplishing code reuse. It allows us to.
C#.Net Software Development Version 1.0. Overview Inheritance Member Access Constructors Polymorphism (Name Hiding) Multilevel Hierarchy Virtual and VTable.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Object-Oriented Concepts
Polymorphism, Interfaces & Operator Overloading
Inheritance and Polymorphism
Week 4 Object-Oriented Programming (1): Inheritance
Interfaces and Inheritance
Designing for Inheritance
Lecture 23 Polymorphism Richard Gesick.
Object-Oriented Programming: Polymorphism
Java Inheritance.
Fundaments of Game Design
Presentation transcript:

Object Oriented Software Development 5. Interfaces, polymorphism and inheritance

Types of interface The word “interface” has more than one meaning in programming User interface The way in which the user interacts with the program Programming interface The way in which software components in an application interact with each other We are looking at the latter here, and will look at the former later on Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 2

Interfaces example InterfaceDemo project Employee.cs ITimeSheet.cs DatabaseTimeSheet.cs FileTimeSheet.cs Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 3

The interface provided by a component In previous examples we saw an Employee class which uses a TimeSheet object Method parameter of type TimeSheet Within its RecordOvertime method an Employee calls the AddEntry method of the TimeSheet object Employee only needs to know that the TimeSheet class provides a method of that name, and the signature of the method Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 4

The interface provided by a component Employee does not need to know anything about how the AddEntry method works Details are hidden behind the class interface Details of how AddEntry works could be changed without affecting Employee If a programmer wants to use the TimeSheet class in another class, only needs to know the class interface Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 5

Documentation of interface Good documentation makes it easy for programmer to understand the interface of a class and how to use it XML comments help to make documentation useful Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 6

Programming to an interface Employee doesn’t care about the details of a TimeSheet, just the interface Make this explicit by defining the interface as an item in its own right Convention (in .NET anyway) is to name the interface with an I - ITimeSheet Refer to the interface name, not the actual object type Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 7

Defining an interface Interface definition Use ITimeSheet as reference type method is empty – no code block Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 8

Defining properties in an interface A property is defined in an interface by specifying the property type, and empty get and/or set declarations Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 9

Rules for interfaces Interfaces can contain: Interfaces can’t contain Methods – declaration only Properties – declaration only Events Interfaces can’t contain Instance variables Constants Constructors Static members Access modifiers Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 10

Implementing an interface Interface doesn’t actually do anything – need to create class which implements the interface Must provide implementation for all members (methods/properties) defined in the interface Class which implements ITimeSheet must (at least) provide a method called AddEntry with the signature defined in ITimeSheet Must provide code block for method Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 11

Implementing an interface “implements ITimeSheet” class can have fields, constructors, etc method has code block Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 12

Implementing multiple interfaces A class can implement more than one interface Class must provide implementations of all the methods declared in all the interfaces it implements Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 13

Interface as a contract A contract is an agreement By implementing an interface, a class agrees that it will provide the defined members This class can then be used by other classes with confidence because they know that it has agreed to provide the required members Employee can use any class which implements ITimeSheet in the knowledge that it will have AddEntry method Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 14

Reference and runtime types Method definition in Employee Method call in Program reference type is ITimeSheet create DatabaseTimeSheet object at runtime pass DatabaseTimeSheet object as parameter at runtime – implements ITimeSheet can call AddEntry because we know runtime type must have agreed to provide this method Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 15

Interface polymorphism Polymorphism means “many forms” Reference to an interface type can point, as the program runs, to any object of a type which implements that interface Can pass any object which implements ITimeSheet as a parameter to RecordOvertime method in Employee Can declare a variable of type ITimeSheet and set it to an object of any type which implements ITimeSheet Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 16

Interface polymorphism interface as reference type alternative implementations of a time sheet can pass any of these objects at runtime when parameter type is ITimeSheet interface can be implemented by class or struct Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 17

Advantages of using interfaces Application code written based on the functionality guaranteed by interface rather than functionality of a particular class Reduces code dependencies Code standardisation Easier to write reusable code Interfaces are used extensively in the .NET Framework library Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 18

Inheritance Often have classes which have some common features e.g. different kinds of employee – SalariedEmployee, HourlyPaidEmployee These are more specific versions of Employee “is-a” relationship – SalariedEmployee is a type of Employee They will share some common features Each will require some specific features Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 19

Inheritance example InheritanceDemo project Employee.cs SalariedEmployee.cs HourlyPaidEmployee.cs Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 20

Inheritance hierarchy generalised base class or superclass inheritance relationships derived classes or subclasses specialised inherits all fields and methods from base class, adds RecordTime method and provides specialised version of Email method inherits all fields and methods from base class and adds payGrade field and PayIncrement method Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 21

Inheritance - object diagram Instance of subclass has all fields defined in subclass and all fields defined in superclass No actual instance of superclass at runtime Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 22

Inheritance hierarchies A class can have many subclasses A class can only have one superclass No multiple inheritance (in C# anyway) Compare this with implementing interfaces Subclass can itself have subclasses Subclass can: Inherit members of superclass Add new members Override members of superclass Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 23

Advantages of using inheritance Reduced code duplication Increased code reuse Models real-world situations Polymorphism Inheritance is used extensively in the .NET Framework library Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 24

.NET base types All .NET types are derived from System.Object class All .NET value types are derived from System.ValueType class System.ValueType is a subclass of System.Object But, inheritance from structs is not allowed Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 25

Implementing inheritance protected – means variables are accessible from subclasses, but not from other classes SalariedEmployee inherits all of these “extends Employee” also define public PayGrade property, other properties inherited Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 26

Subclass constructor Call base class constructor to do initialisation of inherited fields Only need to write code for specific subclass initialisation Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 27

Inherited methods SalariedEmployee and HourlyPaidEmployee both inherit Move method from Employee Can call Move method on instance of subclass Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 28

Added methods HourlyPaidEmployee has additional method RecordTime, which is not in Employee SalariedEmployee does not have this method gives compiler error – emp2 is an instance of SalariedEmployee Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 29

Overriding a method HourlyPaidEmployee has a specialised version of the Email method Constructs email address in a way which is specific to this type of employee Need to override the Email method Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 30

Overriding a method Declare method as virtual in base class Declare method as override in subclass runs method defined in HourlyPaidEmployee runs method defined in Employee Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 31

Abstract classes It is likely in the example that every employee will be one or other of the specific kinds Can declare Employee as an abstract class This means that no instances can be created Abstract classes are meant to be base classes which provide basic functionality to be inherited by concrete classes Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 32

Sealed classes If you don’t want a class to be subclassed, you can declare it as a sealed class Can also define methods as sealed when class is not sealed Subclasses cannot override sealed methods Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 33

Inheritance polymorphism Similar to interface polymorphism Reference to any type can point, as the program runs, to any object of a type which derives from that type Can pass an instance of any subclass of Employee to AddEmployee method in Department Can declare a variable of type Employee and set it to refer to an instance of any subclass of Employee Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 34

Inheritance polymorphism base class as reference type can pass any of these objects at runtime when parameter type is Employee Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 35

Polymorphism and methods Example: reference type is Employee runtime object type is HourlyPaidEmployee You cannot call a method which is not defined in the object’s reference type runs method defined in runtime type* error – method not defined in reference type *the behaviour is different if you use the word new instead of override in the method definition – look up the C# reference and try to find out why Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 36

Casting Solution – cast reference to the runtime type Object type doesn’t change, only reference type Cast must be valid cast operator new reference to same object Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 37

Upcasting and downcasting Upcast (widening) Cast subclass to base class Automatic Downcast (narrowing) Cast base class to subclass Need explicit cast Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 38

Invalid casts In previous slide, compiler reported errors for invalid casts Can have code in which each operation is within the rules, but the result at runtime is invalid This code compiles, but causes a runtime error – why? Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 39

Prefix and As casting Previous example was prefix casting reliable casting reports error (throws exception) if cast is invalid Can use As casting fast casting null reference if cast is invalid – no error reported Specific to .NET! Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 40

When not to use inheritance Inheritance is one of the cornerstones of object oriented programming But... It is not always the right solution for modelling a real-world situation General rule: “don’t use inheritance to model roles” Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 41

Roles Could think of the employees example as follows: Michael is an employee whose role in the company is an hourly paid worker Susan is an employee whose role is a salaried worker Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 42

Changing roles What if Susan’s role is to change, and she is to become an hourly paid worker? We would have to create a whole new HourlyPaidEmployee object to represent her, and remove the existing SalariedEmployee object No representation of the fact that this is still the same person Inheritance is a static structure Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 43

A better way - composition Instead, we could have one object to represent the entity (the employee in this case) and one to represent the role Combine these to represent Susan Can change the combination at runtime Combine Susan’s Employee object with a different role object to change role Employee could have more than one role Composition is a dynamic structure Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 44

Composition roles “has-a” relationships entities provides payGrade field and PayIncrement method and delegates other fields and methods to entity provides RecordTime method and specialised version of Email method and delegates other fields and methods to entity roles “has-a” relationships entities Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 45

Composition - object diagram Instances of role and entity exist at runtime Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 46

Composition compared to inheritance Advantages dynamic structure models changing roles models multiple roles Disadvantages more objects in memory code can be harder to understand Polymorphism doesn’t work (?) Which is better in this example? Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 47

Composition example CompositionDemo HourlyPaidEmployee.cs SalariedEmployee.cs Employee.cs Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 48

Implementing composition Employee class unchanged, except methods are not declared virtual Role classes have instance variable of type Employee Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 49

Delegation of properties/methods Pass a request for EmployeeId property to employee object Pass a call to Move on to employee object Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 50

Constructors Create Employee object then assign it to role object Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 51

Changing role Create new role object and assign existing Employee object to it Could assign another Employee to existing role or set it to null Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 52

Polymorphism How does the example code achieve the advantages of polymorphism even though we have abandoned inheritance? Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 53

Further reading The following links lead to useful articles on interfaces in C#: http://www.c-sharpcorner.com/UploadFile/rmcochran/csharp_interrfaces03052006095933AM/csharp_interrfaces.aspx?ArticleID=cd6a6952-530a-4250-a6d7-54717ef3b345 http://www.csharp-station.com/Tutorials/Lesson13.aspx Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 54

What’s next? We will go on to look at structures for holding collections of similar objects, including arrays and the .NET collection types Some of the concepts introduced in this chapter will be very useful when looking at collections Object Oriented Software Development 5. Interfaces, polymorphism and inheritance 55