University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Inheritance II Lecture 34, Mon Apr 12 2010

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Interfaces, Polymorphism Lecture 20, Tue Mar
CS 211 Inheritance AAA.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Inheritance II Lecture 23, Thu Mar
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Interfaces, Polymorphism II Lecture 21, Thu Mar
ITEC200 – Week03 Inheritance and Class Hierarchies.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Interfaces, Inheritance Lecture 22, Tue Mar
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Advanced Class Design Lecture 19, Thu Mar
Creating Classes from Other Classes Chapter 2 Slides by Steve Armstrong LeTourneau University Longview, TX  2007,  Prentice Hall.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Parameter/Scope Review II, Inheritance Lecture 33,
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Arrays II Lecture 22, Wed Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Interfaces, Polymorphism Lecture 29, Fri Mar
Creating Classes from Other Classes Chapter 2. 2 Chapter Contents Composition Adapters Inheritance Invoking constructors from within constructors Private.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design II Lecture 31, Wed Mar
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Interfaces, Polymorphism Lecture 28, Wed Mar
Abstract Classes and Interfaces
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design III, Parameter/Scope Review Lecture.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
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.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
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.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.
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.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 8 Specialization aka Inheritance. 2 Inheritance  Review of class relationships  Uses – One class uses the services of another class, either.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
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.
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Lecture 12 Inheritance.
Inheritance and Polymorphism
Programming Language Concepts (CIS 635)
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Java Programming Language
Chapter 9 Carrano Chapter 10 Small Java
Presentation transcript:

University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Inheritance II Lecture 34, Mon Apr borrowing from slides by Kurt Eiselt

2 Reading n This week reading: , , n , 11.5, (2nd edition) n we will not get through all this material in lecture n minimal/no coverage on final n weekly reading question still due last class Wed 4/14

3 Recap: Parameter Passing Pictures main method1 4 x foo main method1 x number 4 4 n object as parameter n copy of pointer made n pass by reference n modifications visible outside method n primitive as parameter n copy of value n pass by value n modifications not visible outside method

4 Recap: Static Fields/Methods n Static fields belong to whole class n nonstatic fields belong to instantiated object n Static methods can only use static fields n nonstatic methods can use either nonstatic or static fields class: Giraffe getGiraffeCount() numGiraffes object: Giraffe1 sayHowTall() neckLength object: Giraffe2 sayHowTall() neckLength

5 Recap: Variable Types and Scope n Static variables n declared within class n associated with class, not instance n Instance variables n declared within class n associated with instance n accessible throughout object, lifetime of object n Local variables n declared within method n accessible throughout method, lifetime of method n Parameters n declared in parameter list of method n accessible throughout method, lifetime of method

6 Recap: Inheritance n Inheritance: process by which new class is derived from existing one n fundamental principle of object-oriented programming n Create new child class (subclass) that extends existing parent one (superclass) n inherits all methods and variables n except constructor n can just add new variables and methods

7 Recap: Inheritance and Constructors n Subclass (child class) inherits all methods except constructor methods from superclass (parent class) n Using reserved word super in subclass constructor tells Java to call appropriate constructor method of superclass public class CokeMachine2000 extends CokeMachine2 { public CokeMachine2000() { super(); } public CokeMachine2000(int n) { super(n); } public void loadCoke(int n) { numberOfCans = numberOfCans + n; System.out.println("Adding " + n + " cans to this machine"); }

8 Recap: Inheritance and Scope n Subclasses inherits but cannot directly access private fields or variables of superclass n Protected variables can be directly accessed from declaring class and any classes derived from it

9 Some Coke Machine History early Coke Machine mechanical sealed unit, must be reloaded at factory no protection against vandalism

10 Some Coke Machine History Coke Machine 2000 electro-mechanical can be reloaded on site little protection against vandalism

11 Some Coke Machine History Coke Machine UA* prototype cyberhuman intelligent mobile autonomous vending machine can reload itself in transit vandalism? bring it on * Urban Assault

12 Some Coke Machine History Coke Machine UA Assuming that previous generation CokeMachine simulations have wimpy vandalize() methods built-in to model their gutless behavior when faced with a crowbar-wielding human, how do we create the UA class with true vandal deterrence?

13 Method Overriding n If child class defines method with same name and signature as method in parent class n say child's version overrides parent's version in favor of its own

14 Method Overriding public class CokeMachine2 { private static int totalMachines = 0; protected int numberOfCans; public CokeMachine2() { numberOfCans = 10; System.out.println("Adding another machine to your empire with " + numberOfCans + " cans of Coke"); totalMachines++; } public CokeMachine2(int n) { numberOfCans = n; System.out.println("Adding another machine to your empire with " + numberOfCans + " cans of Coke"); totalMachines++; } public static int getTotalMachines() { return totalMachines; }

15 Method Overriding public int getNumberOfCans() { return numberOfCans; } public void buyCoke() { if (numberOfCans > 0) { numberOfCans = numberOfCans - 1; System.out.println("Have a Coke"); System.out.print(numberOfCans); System.out.println(" cans remaining"); } else { System.out.println("Sold Out"); } public void vandalize() { System.out.println("Please don't hurt me...take all my money"); }

16 Method Overriding public class CokeMachine2000 extends CokeMachine2 { public CokeMachine2000() { super(); } public CokeMachine2000(int n) { super(n); } public void loadCoke(int n) { numberOfCans = numberOfCans + n; System.out.println("loading " + n + " cans"); } public void vandalize() // this overrides the vandalize method from parent { System.out.println("Stop it! Never mind, here's my money"); }

17 Method Overriding public class CokeMachineUA extends CokeMachine2000 { public CokeMachineUA() { super(); } public CokeMachineUA(int n) { super(n); } public void vandalize() // this overrides the vandalize method from parent { System.out.println("Eat lead and die, you slimy Pepsi drinker!!"); }

18 Method Overriding public class SimVend { public static void main (String[] args) { CokeMachine2[] mymachines = new CokeMachine2[5]; mymachines[0] = new CokeMachine2(); mymachines[1] = new CokeMachine2000(); mymachines[2] = new CokeMachineUA(); for (int i = 0; i < mymachines.length; i++) { if (mymachines[i] != null) { mymachines[i].vandalize(); } > java SimVend Adding another machine to your empire with 10 cans of Coke Please don't hurt me...take all my money Stop it! Never mind, here's my money. Eat lead and die, you slimy Pepsi drinker!!

19 Method Overriding n If child class defines method with same name and signature as method in parent class n say child's version overrides parent's version in favor of its own n reminder: signature is number, type, and order of parameters n Writing our own toString() method for class overrides existing, inherited toString() method n Where was it inherited from?

20 Method Overriding n Where was it inherited from? n All classes that aren't explicitly extended from a named class are by default extended from Object class n Object class includes a toString() method n so... class header public class myClass n is actually same as public class myClass extends Object

21 Overriding Variables n You can, but you shouldn't

22 Overriding Variables n You can, but you shouldn't n Possible for child class to declare variable with same name as variable inherited from parent class n one in child class is called shadow variable n confuses everyone! n Child class already can gain access to inherited variable with same name n there's no good reason to declare new variable with the same name

23 Another View of Polymorphism n From Just Java 2 by Peter van der Linden: n Polymorphism is a complicated name for a straightforward concept. It merely means using the same one name to refer to different methods. "Name reuse" would be a better term. n Polymorphism made possible in Java through method overloading and method overriding n remember method overloading?

24 Method Overloading and Overriding n Method overloading: "easy" polymorphism n in any class can use same name for several different (but hopefully related) methods n methods must have different signatures so that compiler can tell which one is intended n Method overriding: "complicated“ polymorphism n subclass has method with same signature as a method in the superclass n method in derived class overrides method in superclass n resolved at execution time, not compilation time n some call it true polymorphism

25 Objectives n Understanding when and how to use abstract classes n Understanding tradeoffs between interfaces and inheritance

26 A New Wrinkle n Expand vending machine empire to include French fry machines n is a French fry machine a subclass of Coke Machine?

27 If We Have This Class Hierarchy... Coke Machine Coke Machine2000 Coke MachineUA is-a

28...Does This Make Sense? Coke Machine Coke Machine2000 Coke MachineUA French Fry Machine is-a

29 Does This Make More Sense? Generic Vending Machine Coke Machine Coke Machine2000 French Fry Machine is-a Coke MachineUA is-a

30 Does This Make More Sense? n Yes n especially if we're thinking of adding all kinds of vending machines... Generic Vending Machine Coke Machine Coke Machine2000 French Fry Machine is-a Coke MachineUA is-a

31 Does This Make More Sense? n Yes n especially if we're thinking of adding all kinds of vending machines... n want our classes to be more specific as we go down class hierarchy n is French Fry Machine more or less specific than Coke Machine? n neither, both specific versions of generic Vending Machine class Generic Vending Machine Coke Machine Coke Machine2000 French Fry Machine is-a Coke MachineUA is-a Pizza Machine Beer Machine is-a

32 Does This Make More Sense? n One way: make a VendingMachine interface like last week n Another way... Generic Vending Machine Coke Machine Coke Machine2000 French Fry Machine is-a Coke MachineUA is-a Pizza Machine Beer Machine is-a

33 Inheritance Solution public class GenericVendingMachine { private int numberOfItems; private double cashIn; public GenericVendingMachine() { numberOfItems = 0; } public boolean vendItem() { boolean result; if (numberOfItems > 0) { numberOfItems--; result = true; } else { result = false; } return result; }

34 Inheritance Solution public void loadItems(int n) { numberOfItems = n; } public int getNumberOfItems() { return numberOfItems; } }

35 Inheritance Solution public class CokeMachine3 extends GenericVendingMachine { public CokeMachine3() { super(); } public CokeMachine3(int n) { super(); this.loadItems(n); } public void buyCoke() { if (this.vendItem()) { System.out.println("Have a nice frosty Coca-Cola!"); System.out.println(this.getNumberOfItems() + " cans of Coke remaining"); } else { System.out.println("Sorry, sold out"); }

36 Inheritance Solution public void loadCoke(int n) { this.loadItems(this.getNumberOfItems() + n); System.out.println("Adding " + n + " ice cold cans of Coke to this machine"); }

37 Inheritance Solution public class CokeMachine2000 extends CokeMachine3 { public CokeMachine2000() { super(); } public CokeMachine2000(int n) { super(); this.loadItems(n); } public void loadCoke(int n) { super.loadCoke(n); System.out.println("Loading in the new millennium!"); }

38 Inheritance From Generic Objects n Want generic VendingMachine class n don’t actually use to generate objects n use as template for specific actual classes like FrenchFryMachine and CokeMachine Generic Vending Machine Coke Machine Coke Machine2000 French Fry Machine is-a Coke MachineUA is-a

39 Inheritance From Generic Objects n Will we ever want to instantiate a generic Vending Machine class? n will we ever need to make generic Vending Machine object? Generic Vending Machine Coke Machine Coke Machine2000 French Fry Machine is-a Coke MachineUA is-a Pizza Machine Beer Machine is-a

40 Inheritance From Generic Objects n Will we ever want to instantiate a generic Vending Machine class? n will we ever need to make generic Vending Machine object? n No, not in our simulated vending world! n How would we use one? What would be a real-life equivalent? Generic Vending Machine Coke Machine Coke Machine2000 French Fry Machine is-a Coke MachineUA is-a Pizza Machine Beer Machine is-a

41 Inheritance From Generic Objects n Introduced CokeMachineUA to combat vandalism and theft n Could just add vandalize() methods to CM, CM2000, CMUA n but we want to ensure that all Vending Machines have vandalize() methods n want all of them to be different n if put into base class at top, easy to have them identical n no way to force method overriding

42 Abstract Classes n Abstract class: not completely implemented n Usually contains one or more abstract methods n has no definition: specifies method that should be implemented by subclasses n just has header, does not provide actual implementation for that method n Abstract class uses abstract methods to specify what interface to descendant classes must look like n without providing implementation details for methods that make up interface n Example: require that all subclasses of VendingMachine class implement vandalize() method n method might differ greatly between one subclass and another n use an abstract method

43 Abstract Classes n Abstract classes serve as place holders in class hierarchy n Abstract class typically used as partial description inherited by all its descendants n Description insufficient to be useful by itself n cannot instantiated if defined properly n Descendent classes supply additional information so that instantiation is meaningful n abstract class is generic concept in class hierarchy n class becomes abstract by including the abstract modifier in class header

44 Abstract Classes n Use abstract class for generic template n can use abstract methods n Making abstract method n Use restricted word abstract in method header n do not provide a method body n just end method header with semicolon

45 Vending Machine Class Revisited public abstract class VendingMachine { private int numberOfItems; public VendingMachine() { numberOfItems = 0; } public boolean vend() { boolean result; if (numberOfItems > 0) { numberOfItems--; result = true; } else { result = false; } return result; } public abstract void vandalize(); }

46 Abstract Methods and Abstract Classes n What happens when we try to compile it all now? n Java tells us that there's an abstract class we have to implement

47 Abstract Methods and Abstract Classes n What happens when we try to compile it all now? n Java tells us that there's an abstract class we have to implement n Could put this CokeMachine class: public void vandalize() { System.out.println("Take all my money, and have a Coke too"); }

48 Abstract Methods and Abstract Classes n What happens when we try to compile it all now? n Java tells us that there's an abstract class we have to implement n Could put this CokeMachine class: public void vandalize() { System.out.println("Take all my money, and have a Coke too"); } n Do we have to implement method in CokeMachine2000 and CokeMachineUA classes too? n Yes, if we want them to behave differently when they're vandalized n original intent

49 Which Organization? Generic Vending Machine Coke Machine Coke Machine2000 French Fry Machine implements extends Coke MachineUA extends Pizza Machine Beer Machine implements

50 Which Organization? Generic Vending Machine Coke Machine Coke Machine2000 French Fry Machine extends Coke MachineUA extends Pizza Machine Beer Machine extends

51 Interfaces vs. Abstract Classes n If we can have abstract class that contains only abstract methods, why do we need interfaces?

52 Interfaces vs. Abstract Classes n If we can have abstract class that contains only abstract methods, why do we need interfaces? n Java does not support multiple inheritance: child classes inheriting attributes from multiple parent classes n other object-oriented languages do n multiple inheritance can be good, but causes problems n what if child class inherits two different methods with same signature from two different parents? n which one should be used?

53 Interfaces vs. Abstract Classes n Java's formal interface provides some of the utility of multiple inheritance without the problems n class can implement more than one interface n can do this at same time it extends class n Interface allows us to create classes that "inherit" features from multiple places

54 Interfaces vs. Abstract Classes n Java's formal interface provides some of the utility of multiple inheritance without the problems n class can implement more than one interface n can do this at same time it extends class n Interface allows us to create classes that "inherit" features from multiple places n Why is problem from previous slide solved? n might have multiple method headers with same signature

55 Interfaces vs. Abstract Classes n Java's formal interface provides some of the utility of multiple inheritance without the problems n class can implement more than one interface n can do this at same time it extends class n Interface allows us to create classes that "inherit" features from multiple places n Why is problem from previous slide solved? n might have multiple method headers with same signature n but only one will have an actual definition n no ambiguity on which will be used n but still could be problem with different return types

56 Interfaces vs. Abstract Classes n Another useful feature provided by interfaces: n inheritance happens between classes that are related n But classes can implement completely unrelated interfaces n and that can be useful

57 Interfaces vs. Abstract Classes n Another useful feature provided by interfaces: n inheritance happens between classes that are related n But classes can implement completely unrelated interfaces n and that can be useful n Example: implement interfaces for n computer, printer, cell phone, vending machine n create class for new interactive vending machines that: n vend Cokes, show annoying music videos, phone their owner when they're running low on product, and spit out coupons for free prizes

58 How Interfaces Differ From Abstract Classes n Abstract class is incomplete class that requires further specialization n interface is just specification or prescription for behavior from Just Java 2 by Peter van der Linden

59 How Interfaces Differ From Abstract Classes n Abstract class is incomplete class that requires further specialization n interface is just specification or prescription for behavior n Inheritance implies specialization, interface does not n interface just implies "We need something that does 'foo' and here are ways that users should be able to call it.“ from Just Java 2 by Peter van der Linden

60 How Interfaces Differ From Abstract Classes n Abstract class is incomplete class that requires further specialization n interface is just specification or prescription for behavior n Inheritance implies specialization, interface does not n interface just implies "We need something that does 'foo' and here are ways that users should be able to call it.“ n Class can implement several interfaces at once n but class can extend only one parent class from Just Java 2 by Peter van der Linden

61 Interfaces vs. Abstract Classes: Bottom Line n Use abstract class to initiate a hierarchy of more specialized classes n Use interface to say, "I need to be able to call methods with these signatures in your class." n Use an interface for some semblance of multiple inheritance from Just Java 2 by Peter van der Linden

62 Interfaces vs. Abstract Classes n Interface can only extend another interface n cannot extend abstract class or "concrete" class n Class can legally implement only some methods of interface if it’s abstract class n then must be further extended through inheritance before can be instantiated from Just Java 2 by Peter van der Linden

63 Who Can Do What? n Interface can be implemented only by class or abstract class n Interface can be extended only by another interface n Class can be extended only by class or abstract class n Abstract class can be extended only by class or abstract class n Only classes can be instantiated as objects n Interfaces are not classes and cannot be instantiated n Abstract classes may have undefined methods and cannot be instantiated