University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner

Similar documents
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

! labs last week. ! still time to work through lab 7 (midterm correction) ! can earn back up to 5 out of 70 points

! labs this week. ! midterms returned. ! work through what you got wrong on midterm. ! can earn back up to 5 out of 70 points

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

! Midterm 2: Thu Mar 16, 6:30pm (TODAY!) ! Woodward 2. ! hour-long exam, reserve 6:30-8 time slot. ! no labs/tutorials this week. ! Bunny.

! This week: Chapter 6 all ( ) ! Formal parameter: in declaration of class. ! Actual parameter: passed in when method is called

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

ECE 122. Engineering Problem Solving with Java

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inheritance -- Introduction

Java Object Oriented Design. CSC207 Fall 2014

Super-Classes and sub-classes

Java Fundamentals (II)

CS 251 Intermediate Programming Inheritance

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Object Oriented Programming. Java-Lecture 11 Polymorphism

COMP 110/L Lecture 19. Kyle Dewey

Abstract Classes and Interfaces

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

ITI Introduction to Computing II

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

Computer Science II (20073) Week 1: Review and Inheritance

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Chapter 6 Introduction to Defining Classes

Assignments. Material Covered. How To Prepare

Introduction to Inheritance

ITI Introduction to Computing II

Inheritance and Interfaces

Building custom components IAT351

CS260 Intro to Java & Android 03.Java Language Basics

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Survey #2. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

JAVA MOCK TEST JAVA MOCK TEST II

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

ECE 122. Engineering Problem Solving with Java

CMSC 132: Object-Oriented Programming II

Declarations and Access Control SCJP tips

CS-202 Introduction to Object Oriented Programming

COP 3330 Final Exam Review

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Data Abstraction. Hwansoo Han

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

C++ Important Questions with Answers

Big software. code reuse: The practice of writing program code once and using it in many contexts.

And Even More and More C++ Fundamentals of Computer Science

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Inheritance. Transitivity

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Chapter 14 Abstract Classes and Interfaces

Class, Variable, Constructor, Object, Method Questions

Survey #2. Variable Scope. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings. Scope Static.

CMSC 132: Object-Oriented Programming II

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

Inheritance and Polymorphism in Java

Programming in C# Inheritance and Polymorphism

Overriding Variables: Shadowing

COMP 250 Fall inheritance Nov. 17, 2017

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Inheritance and Polymorphism

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Midterms Save the Dates!

Midterms Save the Dates!

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Survey #2. Programming Assignment 3. Final Exam. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.

What are the characteristics of Object Oriented programming language?

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Implements vs. Extends When Defining a Class

Inheritance (IS A Relationship)

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

More on Inheritance. Interfaces & Abstract Classes

CSE1720. General Info Continuation of Chapter 9 Read Chapter 10 for next week. Second level Third level Fourth level Fifth level

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

Logistics. Final Exam on Friday at 3pm in CHEM 102

The class Object. Lecture CS1122 Summer 2008

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

1 Shyam sir JAVA Notes

More Relationships Between Classes

Inheritance and Polymorphism. CS180 Fall 2007

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Survey #2. Teen Talk Barbie TM Reloaded. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Partially Filled Arrays ArrayLists

Computer Science 2 Lecture 4 Inheritance: Trinidad Fruit Stand 02/15/2014 Revision : 1.7

Day 5. COMP1006/1406 Summer M. Jason Hinek Carleton University

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

CS 112 Introduction to Programming

CS11 Introduction to C++ Fall Lecture 7

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Transcription:

University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner Inheritance II Lecture 34, Mon Apr 12 2010 borrowing from slides by Kurt Eiselt http://www.cs.ubc.ca/~tmm/courses/111-10 1

Reading This week reading: 2.11-2.12, 9.5-9.8,10.9-10.10 5.1-5.2, 11.5, 12.2-12.3 (2nd edition) we will not get through all this material in lecture minimal/no coverage on final weekly reading question still due last class Wed 4/14 2

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

Recap: Static Fields/Methods Static fields belong to whole class nonstatic fields belong to instantiated object Static methods can only use static fields nonstatic methods can use either nonstatic or static fields class: Giraffe numgiraffes getgiraffecount() object: Giraffe1 necklength sayhowtall() object: Giraffe2 necklength sayhowtall() 4

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

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

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

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

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

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

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

Some History UA Assuming that previous generation 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? 12

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

Method Overriding public class 2 private static int totals = 0; protected int numberofcans; public 2() numberofcans = 10; System.out.println("Adding another machine to your empire with " + numberofcans + " cans of "); totals++; public 2(int n) numberofcans = n; System.out.println("Adding another machine to your empire with " + numberofcans + " cans of "); totals++; public static int gettotals() return totals; 14

Method Overriding public int getnumberofcans() return numberofcans; public void buy() if (numberofcans > 0) numberofcans = numberofcans - 1; System.out.println("Have a "); 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"); 15

Method Overriding public class 2000 extends 2 public 2000() super(); public 2000(int n) super(n); public void load(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"); 16

Method Overriding public class UA extends 2000 public UA() super(); public UA(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!!"); 17

Method Overriding public class SimVend public static void main (String[] args) 2[] mymachines = new 2[5]; mymachines[0] = new 2(); mymachines[1] = new 2000(); mymachines[2] = new UA(); 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 Adding another machine to your empire with 10 cans of Adding another machine to your empire with 10 cans of 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!! 18

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

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

Overriding Variables You can, but you shouldn't 21

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

Another View of Polymorphism From Just Java 2 by Peter van der Linden: 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. Polymorphism made possible in Java through method overloading and method overriding remember method overloading? 23

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

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

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

If We Have This Class Hierarchy... 2000 UA 27

...Does This Make Sense? French Fry 2000 UA 28

Does This Make More Sense? Generic Vending French Fry 2000 UA 29

Does This Make More Sense? French Fry Generic Vending Yes especially if we're thinking of adding all kinds of vending machines... 2000 UA 30

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

Does This Make More Sense? Generic Vending Beer French Fry Pizza One way: make a Vending interface like last week Another way... 2000 UA 32

Inheritance Solution public class GenericVending private int numberofitems; private double cashin; public GenericVending() numberofitems = 0; public boolean venditem() boolean result; if (numberofitems > 0) numberofitems--; result = true; else result = false; return result; 33

Inheritance Solution public void loaditems(int n) numberofitems = n; public int getnumberofitems() return numberofitems; 34

Inheritance Solution public class 3 extends GenericVending public 3() super(); public 3(int n) super(); this.loaditems(n); public void buy() if (this.venditem()) System.out.println("Have a nice frosty Coca-Cola!"); System.out.println(this.getNumberOfItems() + " cans of remaining"); else System.out.println("Sorry, sold out"); 35

Inheritance Solution public void load(int n) this.loaditems(this.getnumberofitems() + n); System.out.println("Adding " + n + " ice cold cans of to this machine"); 36

Inheritance Solution public class 2000 extends 3 public 2000() super(); public 2000(int n) super(); this.loaditems(n); public void load(int n) super.load(n); System.out.println("Loading in the new millennium!"); 37

Inheritance From Generic Objects French Fry Generic Vending Want generic Vending class don t actually use to generate objects use as template for specific actual classes like FrenchFry and 2000 UA 38

Inheritance From Generic Objects Generic Vending Beer French Fry Pizza Will we ever want to instantiate a generic Vending class? will we ever need to make generic Vending object? 2000 UA 39

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

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

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

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

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

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

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

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

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

Which Organization? implements implements Generic Vending implements implements Beer French Fry Pizza extends 2000 extends UA 49

Which Organization? extends extends Generic Vending extends extends Beer French Fry Pizza extends 2000 extends UA 50

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

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

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

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

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

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

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

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

How Interfaces Differ From Abstract Classes Abstract class is incomplete class that requires further specialization interface is just specification or prescription for behavior Inheritance implies specialization, interface does not 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 59

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

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

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

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