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

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

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

! 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.

ITI Introduction to Computing II

ITI Introduction to Computing II

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

ECE 122. Engineering Problem Solving with Java

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

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

Super-Classes and sub-classes

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

CS260 Intro to Java & Android 03.Java Language Basics

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

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

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

Java Object Oriented Design. CSC207 Fall 2014

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

Midterms Save the Dates!

Midterms Save the Dates!

Inheritance, Polymorphism, and Interfaces

JAVA MOCK TEST JAVA MOCK TEST II

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

Introduction to Programming Using Java (98-388)

Review: Object Diagrams for Inheritance. Type Conformance. Inheritance Structures. Car. Vehicle. Truck. Vehicle. conforms to Object

Inheritance -- Introduction

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Java Fundamentals (II)

Programming overview

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

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

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

Introduction to Inheritance

COMP 110/L Lecture 19. Kyle Dewey

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

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

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

CS 61B Data Structures and Programming Methodology. July 2, 2008 David Sun

C++ Important Questions with Answers

COP 3330 Final Exam Review

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

CS11 Introduction to C++ Fall Lecture 7

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

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

Inheritance and Polymorphism

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

ECE 122. Engineering Problem Solving with Java

What is Inheritance?

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

The class Object. Lecture CS1122 Summer 2008

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

What are the characteristics of Object Oriented programming language?

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

CLASS DESIGN. Objectives MODULE 4

CS111: PROGRAMMING LANGUAGE II

Assignments. Material Covered. How To Prepare

Declarations and Access Control SCJP tips

TeenCoder : Java Programming (ISBN )

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

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

CS-202 Introduction to Object Oriented Programming

OVERRIDING. 7/11/2015 Budditha Hettige 82

CIS 110: Introduction to computer programming

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

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

Programming II (CS300)

CompuScholar, Inc. 9th - 12th grades

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Advanced Placement Computer Science. Inheritance and Polymorphism

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

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

Java: introduction to object-oriented features

CS 116 Week 8 Page 1

QUESTIONS FOR AVERAGE BLOOMERS

PROGRAMMING LANGUAGE 2

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

CS 251 Intermediate Programming Inheritance

Polymorphism. return a.doublevalue() + b.doublevalue();

Programming Exercise 14: Inheritance and Polymorphism

Inheritance and Polymorphism. CS180 Fall 2007

Chapter 6 Introduction to Defining Classes

Methods Common to all Classes

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Midterms Save the Dates!

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Midterms Save the Dates!

CMSC 132: Object-Oriented Programming II

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

Chapter 6 Reflection

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

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

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

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

Transcription:

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Interfaces, Inheritance Lecture 22, Tue Mar 28 2006! labs last week News! still time to work through lab 7 (midterm correction)! can earn back up to 5 out of 70 points! rest of Assignment 2 handed back at end of class! Assignment 3 posted! due Friday Apr 7, 5pm! start now, don t wait! based on slides by Kurt Eiselt http://www.cs.ubc.ca/~tmm/courses/cpsc111-06-spr 1 2 Reading! This week: Chap 13, except 13.8.3 Recap: Polymorphism! reference to interface type can reference instance of any class implementing that interface! static type: type that variable declared to be! determines which members of class can be invoked! dynamic type: type that variable actually references! determines which version of method is called 3 4 Correction/Recap: Interfaces as Contract! Can write code that works on anything that fulfills contract! even classes that don t exist yet!! Example: Comparable! useful if you need to sort items! compareto(object)! returns int < 0 if this object less than parameter! returns 0 if same! returns int > 0 if this object greater than parameter 5 Recap: Wrappers! Many classes implement Comparable interface! Byte, Character, Double, Float, Integer, Long, Short, String! each implements own version of compareto! Wrapper classes! wraps up (encapsulates) primitive type! Double: object wrapping primitive double! No: sort( double[] mydata );! Yes: sort( Double[] mydata ); 6

Comparable! sort method that works on array of objects of any type that implements Comparable! type guaranteed to have compareto method! we need to sort! int! String! Bunny! Giraffe!... 7 Multiple Interfaces! Classes can implement more than one interface at once! contract to implement all abstract methods defined in every interface it implements public class MyClass implements Interface1, Interface2, Interface3 8 Objectives! Understanding inheritance! and class hierarchies! Understanding method overriding! and difference with method overloading! Understanding when and how to use abstract classes Vending Science Marches On...! 2 class had limited functionality! buy()! what if run out of cans?! Let s build the Next Generation! just like old ones, but add new exciting load() functionality! How do we create 2000 9 10 Reminder: 2 public class 2 private static int totals = 0; private int numberofcans; public 2() numberofcans = 10; + numberofcans + " cans of "); totals++; public 2(int n) numberofcans = n; + numberofcans + " cans of "); totals++; public static int gettotals() return totals; 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"); 11 One Way: Copy CM2, Change Name,... public class 2000 private static int totals = 0; private int numberofcans; public 2000() numberofcans = 10; + numberofcans + " cans of "); totals++; public 2000(int n) numberofcans = n; + numberofcans + " cans of "); totals++; public static int gettotals() return totals; 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"); 12

...Then Add New Method public void load(int n) numberofcans = numberofcans + n: System.out.println("Adding " + n " " cans to this machine"); Update The Sim Program public class Sim2000 System.out.println(" machine simulator"); 2 cs = new 2(); 2 engr = new 2(237); 2000 chan = new 2000(1); cs.buy(); engr.buy(); chan.buy(); chan.load(150); chan.buy(); 13 14 It Works! > java Sim2000 machine simulator Adding another machine to your empire with 10 cans of Adding another machine to your empire with 237 cans of Adding another machine to your empire with 1 cans of Have a 9 cans remaining Have a 236 cans remaining Have a 0 cans remaining Adding 150 cans to this machine Have a 149 cans remaining Is There An Easier Way......to create a new and improved class from the old class without copying all the code? 15 16...to create a new and improved class from the old class without copying all the code? No. Is There An Easier Way... Is There An Easier Way......to create a new and improved class from the old class without copying all the code? No. OK, I lied. There is an easier way. I'm just checking to see if you're awake. Here's how easy it is. We use the reserved word extends like this... 17 18

Easier Way (First Pass) public class 2000 extends 2 public void load(int n)! Create new class called 2000! inherits all methods and variables from 2! mostly true...we'll see some exceptions later! can just add new variables and methods! Inheritance: process by which new class is derived from existing one! fundamental principle of object-oriented programming Easier Way (First Pass) public class 2000 extends 2 public void load(int n)! Variables and methods in 2 class definition are included in the 2000 definition! even though you can t see them! just because of word extends 19 20 Testing With Sim Easier Way (Second Pass) public class Sim2000 System.out.println(" machine simulator"); 2 cs = new 2(); 2 engr = new 2(237); 2000 chan = new 2000(1); cs.buy(); engr.buy(); chan.buy(); chan.load(150); chan.buy(); 1 error found: File: Sim2000.java [line: 8] Error: cannot resolve symbol symbol : constructor 2000 (int) location: class 2000 OOPS! What happened? 21 public class 2000 extends 2 public 2000() public 2000(int n) public void load(int n)! 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! also makes our intentions with respect to constructors explicit 22 Testing Second Pass public class 2000 extends 2 public 2000() public 2000(int n) public void load(int n) 2 errors found: File: 2000.java [line: 15] Error: numberofcans has private access in 2 File: 2000.java [line: 15] Error: numberofcans has private access in 2 23 Easier Way (Third Pass) public class 2000 extends 2 public 2000() public 2000(int n) public void load(int n)! Subclass inherits all variables of superclass! But private variables cannot be directly accessed, even from subclass public class 2 private static int totals = 0; private int numberofcans; 24

Easier Way (Third Pass) public class 2000 extends 2 public 2000() public 2000(int n) public void load(int n)! Simple fix: change access modifier to protected in superclass definition! protected variables can be directly accessed from declaring class and any classes derived from it public class 2 private static int totals = 0; protected int numberofcans;... 25 Testing With Sim public class Sim2000 System.out.println(" machine simulator"); 2 cs = new 2(); 2 engr = new 2(237); 2000 chan = new 2000(1); cs.buy(); engr.buy(); chan.buy(); chan.load(150); chan.buy(); 26 Testing With Sim public class Sim2000 System.out.println(" machine simulator"); 2 cs = new 2(); 2 engr = new 2(237); 2000 chan = new 2000(1); cs.buy(); engr.buy(); chan.buy(); chan.load(150); chan.buy(); > java Sim2000 machine simulator Adding another machine to your empire with 10 cans of Adding another machine to your empire with 237 cans of Adding another machine to your empire with 1 cans of Have a 9 cans remaining Have a 236 cans remaining Have a 0 cans remaining Adding 150 cans to this machine Have a 149 cans remaining 27 > Some History early mechanical sealed unit, must be reloaded at factory no protection against vandalism 28 Some History Some History 2000 electro-mechanical can be reloaded on site little protection against vandalism UA* prototype cyberhuman intelligent mobile autonomous vending machine can reload itself in transit vandalism? bring it on * Urban Assault 29 30

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?! 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 31 32 public class 2 private static int totals = 0; protected int numberofcans; public int getnumberofcans() return numberofcans; public 2() numberofcans = 10; + numberofcans + " cans of "); totals++; public 2(int n) numberofcans = n; + numberofcans + " cans of "); totals++; public static int gettotals() return totals; 33 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"); 34 public class 2000 extends 2 public 2000() public class UA extends 2000 public UA() public 2000(int n) public UA(int n) public void load(int n) System.out.println("loading " + n + " cans"); public void vandalize() // this overrides the vandalize method from parent System.out.println("Eat lead and die, you slimy Pepsi drinker!!"); public void vandalize() // this overrides the vandalize method from parent System.out.println("Stop it! Never mind, here's my money"); 35 36

public class SimVend 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!! 37! 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? 38 Overriding Variables! 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! You can, but you shouldn't 39 40 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 41 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? 42

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 43 A New Wrinkle! Expand vending machine empire to include French fry machines! is a French fry machine a subclass of? 44 If We Have This Class Hierarchy......Does This Make Sense? 2000 French Fry 2000 UA UA 45 46 Does This Make More Sense? Does This Make More Sense? Generic Vending Generic Vending French Fry 2000 UA 47 French Fry! Want generic Vending class! don t actually use to generate objects! use as template for specific actual classes like FrenchFry and 2000 UA 48

Does This Make More Sense? 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! One way: make a Vending interface like last week! Another way... 2000 UA 49! 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 50 public abstract class GenericVending private int numberofitems; private double cashin; public GenericVending() numberofitems = 0; public void loaditems(int n) numberofitems = n; public int getnumberofitems() return numberofitems; public boolean venditem() boolean result; if (numberofitems > 0) numberofitems--; result = true; else result = false; return result; 51 52 public class 3 extends Vending public 3() public 3(int n) this.loaditems(n); public void load(int n) this.loaditems(this.getnumberofitems() + n); System.out.println("Adding " + n + " ice cold cans of to this machine"); 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"); 53 54