Question? Leave a message!

Interfaces, polymorphism and inheritance

Interfaces, polymorphism and inheritance
Object Oriented Software Development 5. Interfaces, polymorphism and inheritance www.ThesisScientist.comTypes 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 www.ThesisScientist.comInterfaces example  InterfaceDemo project  Employee.cs  ITimeSheet.cs  DatabaseTimeSheet.cs  FileTimeSheet.cs www.ThesisScientist.comThe 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 www.ThesisScientist.comThe 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 www.ThesisScientist.comDocumentation 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 www.ThesisScientist.comProgramming 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 www.ThesisScientist.comDefining an interface  Interface definition method is empty – no code block  Use ITimeSheet as reference type www.ThesisScientist.comDefining properties in an interface  A property is defined in an interface by specifying the property type, and empty get and/or set declarations www.ThesisScientist.comRules for interfaces  Interfaces can contain:  Methods – declaration only  Properties – declaration only  Events  Interfaces can’t contain  Instance variables  Constants  Constructors  Static members  Access modifiers www.ThesisScientist.comImplementing 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 www.ThesisScientist.comImplementing an interface “implements ITimeSheet” class can have fields, constructors, etc method has code block www.ThesisScientist.comImplementing 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 www.ThesisScientist.comInterface 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 www.ThesisScientist.comReference and runtime types  Method definition in Employee reference type is ITimeSheet create DatabaseTimeSheet  Method call in Program object at runtime pass DatabaseTimeSheet object as can call AddEntry because we parameter at runtime – implements know runtime type must have ITimeSheet agreed to provide this method www.ThesisScientist.comInterface 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 www.ThesisScientist.comInterface 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 www.ThesisScientist.comAdvantages 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 www.ThesisScientist.comInheritance  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 www.ThesisScientist.comInheritance example  InheritanceDemo project  Employee.cs  SalariedEmployee.cs  HourlyPaidEmployee.cs www.ThesisScientist.comInheritance hierarchy Employee generalised -employeeId base class or -name -username superclass -phoneNumber +Move() +Email() inheritance relationships HourlyPaidEmployee SalariedEmployee derived classes -payGrade +RecordTime() or subclasses +PayIncrement() +Email() specialised inherits all fields and methods from base inherits all fields and methods from base class, adds RecordTime method and provides class and adds payGrade field and specialised version of Email method PayIncrement method www.ThesisScientist.comInheritance - object diagram  Instance of subclass has all fields defined in subclass and all fields defined in superclass  No actual instance of superclass at runtime emp1 : HourlyPaidEmployee employeeId = 1 name : string = Michael username : string = michael phoneNumber : string = 1234 loc : Location emp2 : SalariedEmployee employeeId = 2 name : string = Susan username : string = susan phoneNumber : string = 4321 payGrade : int = 6 www.ThesisScientist.comInheritance 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 www.ThesisScientist.comAdvantages of using inheritance  Reduced code duplication  Increased code reuse  Models real-world situations  Polymorphism  Inheritance is used extensively in the .NET Framework library 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 www.ThesisScientist.comImplementing 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 www.ThesisScientist.comSubclass constructor  Call base class constructor to do initialisation of inherited fields  Only need to write code for specific subclass initialisation www.ThesisScientist.comInherited methods  SalariedEmployee and HourlyPaidEmployee both inherit Move method from Employee  Can call Move method on instance of subclass www.ThesisScientist.comAdded 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 www.ThesisScientist.comOverriding 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 www.ThesisScientist.comOverriding 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 www.ThesisScientist.comAbstract 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 www.ThesisScientist.comSealed 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 www.ThesisScientist.comInheritance 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 www.ThesisScientist.comInheritance polymorphism base class as reference type can pass any of these objects at runtime when parameter type is Employee www.ThesisScientist.comPolymorphism and methods  Example:  reference type is Employee  runtime object type is HourlyPaidEmployee runs method defined in runtime type error – method not defined in reference type  You cannot call a method which is not defined in the object’s 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 www.ThesisScientist.comCasting  Solution – cast reference to the runtime type cast operator  Object type doesn’t change, only reference type new reference to same object HourlyPaidEmployee hpemp:HourlyPaidEmployee emp:Employee  Cast must be valid www.ThesisScientist.comUpcasting and downcasting  Upcast (widening)  Cast subclass to base class  Automatic  Downcast (narrowing)  Cast base class to subclass  Need explicit cast www.ThesisScientist.comInvalid 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? www.ThesisScientist.comPrefix 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 www.ThesisScientist.comWhen 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” www.ThesisScientist.comRoles  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 www.ThesisScientist.comChanging 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 www.ThesisScientist.comA 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 www.ThesisScientist.comComposition provides RecordTime method and specialised provides payGrade field and PayIncrement version of Email method and delegates other method and delegates other fields and fields and methods to entity methods to entity HourlyPaidEmployee SalariedEmployee -payGrade roles +RecordTime() +PayIncrement() +Email() -employee -employee “has-a” relationships Employee -employeeId -name -username entities -phoneNumber +Move() +Email() www.ThesisScientist.comComposition - object diagram  Instances of role and entity exist at runtime emp1.Employee : Employee employeeId = 1 name : string = Michael emp1 : HourlyPaidEmployee username : string = michael phoneNumber : string = 1234 loc : Location emp2.Employee : Employee employeeId = 2 name : string = Susan emp2 : SalariedEmployee username : string = susan payGrade : int = 6 phoneNumber : string = 4321 www.ThesisScientist.comComposition 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? www.ThesisScientist.comComposition example  CompositionDemo  HourlyPaidEmployee.cs  SalariedEmployee.cs  Employee.cs www.ThesisScientist.comImplementing composition  Employee class unchanged, except methods are not declared virtual  Role classes have instance variable of type Employee www.ThesisScientist.comDelegation of properties/methods  Pass a request for EmployeeId property to employee object  Pass a call to Move on to employee object www.ThesisScientist.comConstructors  Create Employee object then assign it to role object www.ThesisScientist.comChanging role  Create new role object and assign existing Employee object to it  Could assign another Employee to existing role or set it to null www.ThesisScientist.comPolymorphism  How does the example code achieve the advantages of polymorphism even though we have abandoned inheritance? www.ThesisScientist.comFurther reading  The following links lead to useful articles on interfaces in C:  http://www.c- terrfaces03052006095933AM/csharp_interrfaces. aspx?ArticleID=cd6a6952-530a-4250-a6d7- 54717ef3b345  http://www.csharp- www.ThesisScientist.comWhat’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
Website URL
Document Information
User Name:
User Type:
Uploaded Date: