260 likes | 380 Views
CET203 SOFTWARE DEVELOPMENT. Session 3A Abstract classes and Polymorphism. Objectives. Understand the concept of abstract classes Use polymorphism to handle related classes in a generalized way Understand the implications of polymorphism with overridden methods. Abstract classes.
E N D
CET203SOFTWARE DEVELOPMENT Session 3A Abstract classes and Polymorphism
Objectives • Understand the concept of abstract classes • Use polymorphism to handle related classes in a generalized way • Understand the implications of polymorphism with overridden methods
Abstract classes • Publication will never be instantiated – we will never create objects of this type • The class exists to gather together the generalized features of its subclasses in one place for them to inherit. • We can enforce the fact that Publication is non-instantiable by declaring it ‘abstract’: abstract class Publication { // etc.
Abstract Publication <<abstract>> Publication Abstract Class title price copies SellCopy() Magazine Book orderQty currIssue author AdjustQty() RecvNewIssue() OrderCopies() DiscMag RecvNewIssue()
Exercise 1 Publications2A.sln
Exercise 1 • If Publication is an abstract class which of the following statements would be legal: Book book1 = new Book("Software Development“, 10.99, 3, "Liz Gandy"); DiscMag dmag1 = new DiscMag("C# programming", 2.5, 10, 10, "September"); Publication pub1 = new Publication("Programming in C#", 20.5, 1); Magazine mag1 = new Magazine("C# monthly", 2.5, 10, 10, "September");
Recap: Biological classification • Kingdom (e.g. animals) • Phylum (e.g. vertebrates) • Class (e.g. mammal) • Order (e.g. artiodactyla) • Family (e.g. suidae) • Genus (e.g. sus) • Species (e.g. sus scrofa) • Pinky the pig is a…
“is a” • Within hierarchical classification of animals • Pinkyis a pig (species susscrofa) • Pinkyis (also, more generally) a mammal • Pinkyis (also, even more generally) a vertebrate • We can specify the type of thing an organism is at different levels of detail: • higher level = less specific • lower level = more specific • Pinky has a backbone, and suckles her young, and goes “oinkoink”.
Exercise 2 • How would we fit together the following in a hierarchy (using “is a” statements): • “guitar” • “acoustic guitar” • “musical instrument” • “electric guitar” • “stringed instrument” • “my guitar” [electrically amplified] • Draw a class diagram for this hierarchy (just show class names and relationships, no attributes or operations!) • Show on your class diagram which classes might be abstract?
Pigs(Three Different Ones) • An object in a classification hierarchy has an ‘is a’ relationship with every class from which it is descended. • If I ask you to give me a pig • you could give me Pinky • or any other pig • If I ask you to give me a mammal • you could give me Perky • or any other pig • or any other mammal (e.g. any lion, or any mouse, or any human being!) • If I ask you to give me an animal • you could give me Porky • or… (etc!)
Class Types & Roles • Every time we define a class we create a new ‘type’ • Types determine compatibility between variables, parameters etc. • A subclass type is a subtype of the superclass type • We can substitute a subtype wherever a ‘supertype’ is expected • If the type is a superclass, any subclass can fill the role because they are each subtypes • The reverse is not true!
Exercise 3 Publication • Consider the following objects: Book myBook; Magazine myMag; DiscMagmyDiscMag; • Fill in the gaps: If I asked you to give me a book you could give me ___ or any other object of type ____ If I asked you to give me a discMag you could give me ___ or any other object of type ____ If I ask you to give me a magazine you could give me ___ or ____ or any other object of type ____ If I asked you to give me a publication you could give me ___ or ___ or ___ or any other object of type ____ Book Magazine DiscMag
Substitutability • When designing class/type hierarchies, the type mechanism allows us to place a subclass object where a superclass is specified • This has implications for the design of subclasses – we need to make sure they are genuinely substitutable for the superclass • For example, a method should not be overridden with functionality which performs an inherently different operation
Example • RecvNewIssue() in DiscMag overrides RecvNewIssue() from Magazine but does the same basic job (“fulfils the contract”) as the inherited version with respect to updating the number of copies and the current issue. • However, it extends that functionality in a way specifically relevant to DiscMags by displaying a reminder to check the cover discs.
Q: What do we know about a ‘Publication’? • A: It’s an object which supports (at least) the operations: • SellCopy() • ToString() • A: It’s an object which has (at least) the properties: • Title • Price • Copies • Inheritance guarantees that objects of any subclass of Publications provides at least these. • A subclass can never remove an operation inherited from its superclass(es) – this would break the guarantee. • Because subclasses extend the capabilities of their superclasses, the superclass functionality can be assumed.
Polymorphism • Because an instance of a subclass is an instance of its superclass we can handle subclass objects as if they were superclass objects. • Because a superclass guarantees certain operations in its subclasses we can invoke those operations without caring of which subclass the actual object is an instance. • This characteristic is termed ‘polymorphism’, originally meaning ‘having multiple shapes’.
Operations • If p ‘is a’ Publication, it might be a Book or a Magazine or a DiscMag. • Whichever, it has a SellCopy() method. • So we can invoke p.SellCopy() without worrying about what exactly p is. • This can make life a lot simpler when we are manipulating objects within an inheritance hierarchy.
CashTill • We want to develop a class CashTill which processes a sequence of items being sold. • Without polymorphism we would need separate methods for each type of item: SellBook(Book book) SellMagazine(Magazine magazine) SellDiscMag(DiscMagdiscMag) • With polymorphism we need only SellItem(Publication pub) • An object of any of the subclasses of Publication can be passed as a Publication parameter
Publications sell themselves! • Without polymorphism we would need to check for each item p so we were calling the right method to sell a copy of that subtype if p is a Book call SellCopy() method for Book else if p is a Magazine call SellCopy() method for Magazine else if p is a DiscMag call SellCopy() method for DiscMag • Instead we trust p to know its own type and its own method for selling itself call p.SellCopy()
Class Diagram with CashTill <<abstract>> Publication CashTill title : String price : double copies : int runningTotal : double SellCopy() SellItem(pub : Publication) ShowTotal() Magazine Book orderQty : int currIssue : String Author : String AdjustQty(quantity : int) RecvNewIssue(newIssue : String) OrderCopies(copies : int) DiscMag RecvNewIssue(newIssue : String)
Implementing CashTill (1) class CashTill { // INSTANCE VARIABLES ********************* private double runningTotal; // Constructor CashTill() { runningTotal= 0; }
Implementing CashTill (2) public void SellItem(Publication pub) { String msg; runningTotal= runningTotal+ pub.Price; pub.SellCopy(); msg = "Sold " + pub+ " @ “ + pub.Price+ "\nSubtotal = " + runningTotal; Console.WriteLine(msg); } The version of SellCopy() called depends on which type of Publication has been passed into pub Calls appropriate class’s overridden ToString()
Implementing CashTill (3) public void ShowTotal() { Console.WriteLine("GRAND TOTAL: " + runningTotal); runningTotal= 0; }
Exercise 4 Publications2B.sln
Exercise 4 • Assuming the following objects have been declared: CashTillmyTill= new CashTill(); Book book1 = new Book("Software Development", 10.99, 3, "Liz Gandy"); Book book2 = new Book("Programming in C#", 20.5, 1, "Linda White"); Magazine mag1 = new Magazine("C# monthly", 2.5, 10, 10, "September"); DiscMag dmag1 = new DiscMag("C# programming", 2.5, 10, 10, "September"); • Write the code statements to sell one copy of each item through the CashTill and then show the overall total
Summary • Polymorphism allows us to refer to objects according to a superclass rather than their actual class. • Inheritance guarantees that operations available for the superclass are available in its subclasses. • We can manipulate objects by invoking operations defined for the superclass without worrying about which subclass is involved in any specific case. • C# ensures that the appropriate method for the actual class of the object is invoked at run-time.