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

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

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

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

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

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

! 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

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Midterms Save the Dates!

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

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

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

CS 180 Fall 2008 Exam II

University of Palestine. Mid Exam Total Grade: 100

Midterms Save the Dates!

Handout 7. Defining Classes part 1. Instance variables and instance methods.

Midterms Save the Dates!

CS 302 Week 9. Jim Williams

ECE 122. Engineering Problem Solving with Java

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Review questions. Review questions, cont d. Class Definition. Methods. Class definition: methods. April 1,

Midterms Save the Dates!

COMP-202 Unit 9: Exceptions

! Rest of Chap 2 ! 2.3-4, ! Rest of Chap 4 ! ! Things that do not vary. ! unlike variables. ! will never change. !

Assignments. Material Covered. How To Prepare

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

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

Using Classes and Objects. Lecture 7. Midterms Save the Dates! Extra Credit Survey

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Understanding class definitions. Looking inside classes (based on lecture slides by Barnes and Kölling)

JAVA OPERATORS GENERAL

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

COMP-202 Unit 9: Exceptions

public class TicketMachine Inner part omitted. public class ClassName Fields Constructors Methods

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

Lecture 5: Methods CS2301

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

University of Massachusetts Amherst, Electrical and Computer Engineering

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

Distributed Systems Recitation 1. Tamim Jabban

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

Midterms Save the Dates!

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

Programming Language (2) Lecture (4) Supervisor Ebtsam AbdelHakam Department of Computer Science Najran University

COMP 250 Winter 2011 Reading: Java background January 5, 2011

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016

coe318 Lab 2 ComplexNumber objects

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

PeerWise Study. Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Constants Using Classes and Objects

Programming Basics. Digital Urban Visualization. People as Flows. ia

Today s Agenda. Quick Review

CS Week 13. Jim Williams, PhD

Selenium Class 9 - Java Operators

Midterms Save the Dates!

MIDTERM REVIEW. midterminformation.htm

Place your name tag here

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

CS 101 Exam 2 Spring Id Name

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

Slide 1 CS 170 Java Programming 1

COE318 Lecture Notes Week 8 (Oct 24, 2011)

Java and OOP. Part 2 Classes and objects

CMPS 12A - Winter 2002 Midterm 2 March 5, Name: ID:

Object Oriented Programming

CS121/IS223. Object Reference Variables. Dr Olly Gotel

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Midterms Save the Dates!

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

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)

Methods. Eng. Mohammed Abdualal

Java Simple Data Types

Object Oriented Programming

ENGR 2710U Midterm Exam UOIT SOLUTION SHEET

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

COMP-202: Foundations of Programming. Lecture 26: Review; Wrap-Up Jackie Cheung, Winter 2016

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

1.00 Lecture 6. Java Methods

Prof. Navrati Saxena TA: Rochak Sachan

Object-Oriented Programming and Software Engineering CITS1001 MID-SEMESTER TEST

CS 101 Fall 2005 Midterm 2 Name: ID:

Practice Questions for Chapter 9

Utilities (Part 2) Implementing static features

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

1 Shyam sir JAVA Notes

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

CS101 Part 2: Practice Questions Algorithms on Arrays, Classes and Objects, String Class, Stack Class

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

16. Give a detailed algorithm for making a peanut butter and jelly sandwich.

Class, Variable, Constructor, Object, Method Questions

CS Week 14. Jim Williams, PhD

CS 231 Data Structures and Algorithms, Fall 2016

CS 11 java track: lecture 3

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

CMPS 12A Introduction to Programming Midterm 2 Review Problems

Anatomy of a Class Encapsulation Anatomy of a Method

Transcription:

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Interfaces, Polymorphism Lecture 20, Tue Mar 21 2006 based on slides by Kurt Eiselt http://www.cs.ubc.ca/~tmm/courses/cpsc111-06-spr 1

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

Recap: Parameter Passing object as parameter: copy of pointer made main prim as parameter: copy of value main foo method1 x 4 4 number 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 acessible throughout method, lifetime of method 5

Recap: Variable Types Static? Instance? Local? Parameters? class: Giraffe int numgiraffes getgiraffecount() object: Giraffe1 int necklength sayhowtall() object: Giraffe2 int necklength sayhowtall() yell(string message) int volume yell(string message) int volume 6

Here's a puzzler... How does System.out.println() accept different data types as parameters? public class PrintlnTest public static void main(string[] args) int a = 7; double b = 3.14159; boolean c = false; String d = "woohoo!"; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); > java PrintlnTest 7 3.14159 false woohoo! 7

Here's a puzzler... How does System.out.println() accept different data types as parameters? public class PrintlnTest public static void main(string[] args) int a = 7; double b = 3.14159; boolean c = false; String d = "woohoo!"; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); > java PrintlnTest 7 3.14159 false woohoo! 8

Here's a puzzler... How does System.out.println() accept different data types as parameters? public class PrintlnTest public static void main(string[] args) int a = 7; double b = 3.14159; boolean c = false; String d = "woohoo!"; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); In other words, why doesn't this blow up? Can you construct a method that will accept different data types? 9

Method overloading Java allows us to create methods with the same name but different parameter lists. This is useful when you want to perform similar operations on different types of data as well as different numbers of parameters. This is called method overloading. 10

Method overloading - different types public class OverloadTest public static void main(string[] args) int a = 7; boolean c = false; String d = "woohoo!"; test(a); test(c); test(d); public static void test(int x) System.out.println("I am an integer."); public static void test(boolean x) System.out.println("Am I a boolean? Yes? No?"); public static void test(string x) System.out.println("Aye, I'm a String and proud of it!"); 11

Method overloading - param list length public class AvgTest public static void main(string[] args) System.out.println(avg (10, 30, 20)); System.out.println(avg(30,20)); public static double avg(double a, double b) return ((a + b) / 2); public static double avg(double a, double b, double c) return ((a + b + c) / 3); 12

Method overloading When two or more methods have the same name, Java uses the number of parameters, the types of the parameters, and/or the order of the types of parameters to distinguish between the methods. The method's name, type, and order of its parameters is called its signature. If you try to create two methods with the same signature, the compiler will let you know. 13

Method overloading public class AvgTest2 public static void main(string[] args) System.out.println(avg(30,20)); public static double avg(double a, double b) return ((a + b) / 2); public static double avg(double a, double b) // same signature return ((a + b) / 2.0); // different logic 14

Method overloading public class AvgTest2 public static void main(string[] args) System.out.println(avg(30,20)); public static double avg(double a, double b) return ((a + b) / 2); public static double avg(double a, double b) // same signature return ((a + b) / 2.0); // different logic 1 error found: File: AvgTest2.java [line: 13] Error: avg(double,double) is already defined in AvgTest2 15

Method overloading When two or more methods have the same name, Java uses the number of parameters, the types of the parameters, and/or the order of the types of parameters to distinguish between the methods. The method's name, type, and order of its parameters is called its signature. If you try to create two methods with the same signature, the compiler will let you know. The return type is not part of the signature. That is, you can't have two overloaded methods whose signatures differ only by the return type. Why? There's no way for Java to know from the method invocation which method was intended to be used, and it's not going to choose one at random, is it? 16

Method overloading public class AvgTest3 public static void main(string[] args) System.out.println(avg(30,20)); public static double avg(double a, double b) return ((a + b) / 2); public static float avg(double a, double b) // same signature // different return type return ((a + b) / 2); 2 errors found: File: AvgTest3.java [line: 13] Error: avg(double,double) is already defined in AvgTest3 File: AvgTest3.java [line: 15] Error: possible loss of precision found : double required: float 17

Constructor overloading Can we overload constructor methods? Of course! Here's our favourite program, the CokeMachine... public class CokeMachine2 private static int totalmachines = 0; private int numberofcans; public CokeMachine2() numberofcans = 10; System.out.println("Adding another machine to your empire with " + numberofcans + " cans of Coke"); totalmachines++; 18

Constructor overloading public static int gettotalmachines() return totalmachines; 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"); 19

Constructor overloading public class CokeMachine2 private static int totalmachines = 0; private 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++; 20

Constructor overloading public class SimCoke2 public static void main (String[] args) System.out.println("Coke machine simulator"); CokeMachine2 cs = new CokeMachine2(); CokeMachine2 engr = new CokeMachine2(237); CokeMachine2 chan = new CokeMachine2(42); CokeMachine2 library = new CokeMachine2(9000); cs.buycoke(); engr.buycoke(); > java SimCoke2 Coke machine simulator Adding another machine to your empire with 10 cans of Coke Adding another machine to your empire with 237 cans of Coke Adding another machine to your empire with 42 cans of Coke Adding another machine to your empire with 9000 cans of Coke Have a Coke 9 cans remaining Have a Coke 236 cans remaining 21

Another vending-related opportunity Let's say that you've been inspired by CPSC 111 and decide to create commercial vendingmachine simulation software. To make this work, you'll need to accommodate vending machines beyond those that sell only Coca-Cola products. For example, you may want to include... 22

Pizza machines... 23

Beer machines... 24

...and even French fry machines! 25

Another vending-related opportunity Furthermore, while recognizing that a pizza machine is not the same as a beer machine is not the same as a Coke machine, you'll want to take advantage of the fact these two distinct types of vending machines have much in common. How can you do this? Here's one way... 26

Interfaces Informally, we've used the word "interface" to refer to the set of public methods (for example, getters and setters) through which we interact with an object. There's also a more formal use of the word interface in Java. A Java interface is a collection of constants and abstract methods. 27

Interfaces An abstract method has no implementation...no body. It's just a method header followed by a semicolon. It specifies how one communicates with a method, but not what the method does. 28

Interfaces public interface VendingMachine public void venditem(); public int getitemsremaining(); public int getitemssold(); public double getcashreceived(); public void loaditems(int n); We create an interface by using the reserved word interface in what would be the class header, if an interface were a class (which it's not...think of it more as the syntactic specification for a class). 29

Interfaces public interface VendingMachine public abstract void venditem(); public abstract int getitemsremaining(); public abstract int getitemssold(); public abstract double getcashreceived(); public abstract void loaditems(int n); We could use the reserved word abstract in the abstract method headers, but we don't have to because the methods in an interface must be abstract. 30

Interfaces An interface is not a class. An interface only prescribes what methods some other class or classes must have. That is, an interface specifies the headings for methods that must be defined in any class that implements the interface, but it doesn't say what happens inside the methods. from Absolute Java by Walter Savitch. 31

Implementing an interface A class implements an interface by providing method implementations for each of the abstract methods defined in the interface. A class that implements an interface uses the reserved word implements followed by the interface name in the class header. 32

Implementing an interface public class CokeMachine2005 implements VendingMachine private int itemsremaining; private int itemssold; private double cashreceived; public CokeMachine2005() itemsremaining = 10; itemssold = 0; cashreceived = 0; System.out.println("Adding another CokeMachine to your empire"); public int getitemsremaining() return itemsremaining; public int getitemssold() return itemssold; 33

Implementing an interface public double getcashreceived() return cashreceived; public void loaditems(int n) itemsremaining += n; public void venditem() if (itemsremaining > 0) itemsremaining = itemsremaining - 1; itemssold++; cashreceived = cashreceived + 1.25; System.out.println("Have a Coke"); System.out.print(itemsRemaining); System.out.println(" cans remaining"); else System.out.println("Sold out."); 34

Implementing an interface public class FrenchFryMachine2005 implements VendingMachine private int itemsremaining; private int itemssold; private double cashreceived; public FrenchFryMachine2005() itemsremaining = 10; itemssold = 0; cashreceived = 0; System.out.println("Adding another FrenchFryMachine to your empire"); public int getitemsremaining() return itemsremaining; public int getitemssold() return itemssold; 35

Implementing an interface public double getcashreceived() return cashreceived; public void loaditems(int n) itemsremaining += n; public void venditem() if (itemsremaining > 0) itemsremaining = itemsremaining - 1; itemssold++; cashreceived = cashreceived + 1.00; System.out.println("Have a nice hot cup of french fries"); System.out.print(itemsRemaining); System.out.println(" cups of french fries remaining"); else System.out.println("Sold out."); 36

Implementing an interface For a class to implement an interface, it must provide a definition for all methods in the interface. If there are unimplemented methods, the class must be declared to be an abstract class, but that's a topic for another time. 37

What do these relationships look like? Generic Vending Machine Beer Machine French Fry Machine Coke Machine Pizza Machine 38

Why this stuff is very very cool* Because an object of a class that implements an interface is also an object of that interface type. That concept is the basis of an important object-oriented programming principle called polymorphism. Polymorphism is derived from the word fragment poly and the word morpho in Greek, and it literally means "multiple forms". *assuming you come from the planet Nerdtron 39

Why this stuff is very very cool Polymorphism simplifies the processing of various objects in the same class hierarchy by using the same method call for any object in the hierarchy. We make the method call using an object reference of the interface. At run time, the Java Virtual Machine determines which class in the hierarchy the object actually belongs to and invokes the version of the method implemented for that class. from Java 5 Illuminated by Anderson and Franceschi 40

Why this stuff is very very cool public class SimCoke2005 public static void main (String[] args) VendingMachine foo1 = new CokeMachine2005(); VendingMachine foo2 = new FrenchFryMachine2005(); foo1.venditem(); foo2.venditem(); Adding another CokeMachine to your empire Adding another FrenchFryMachine to your empire Have a Coke 9 cans remaining Have a nice hot cup of french fries 9 cups of french fries remaining 41

Why this stuff is very very cool public class SimCoke2005 public static void main (String[] args) VendingMachine foo1 = new CokeMachine2005(); VendingMachine foo2 = new FrenchFryMachine2005(); foo1.venditem(); foo2.venditem(); The little foos may look like VendingMachine objects to you and me, but Java knows the difference and finds the appropriate method for each foo. That makes our programming job a lot easier to do. Why? 42

Why this stuff is very very cool Because the alternative is to write lots of chunks of code that look like sort of like this (if they were written in English): if we want to vend an item from foo1 and foo1 is a CokeMachine2005 then print "have a Coke" else if we want to vend an item from foo1 and foo1 is a FrenchFryMachine2005 then print "have a cup of french fries" else if we want to vend an item from foo1 and foo1 is a PizzaMachine2005 then... As the number of classes within the same hierarchy grows, so does the size of the chunks of code represented above. Eeyow! 43

A simple bunny example public interface Bunnies public void movebunny(int direction); 44

A simple bunny example public class BigBunny implements Bunnies private int x, y; private int carrots; public BigBunny() x = 5; y = 5; carrots = 10; public void movebunny(int direction) if (direction == 12) y = y + 3; carrots = carrots - 2; 45

A simple bunny example else if (direction == 3) x = x + 3; carrots = carrots - 2; else if (direction == 6) y = y - 3; carrots = carrots - 2; else if (direction == 9) x = x - 3; carrots = carrots - 2; else System.out.println("Invalid direction"); 46

A simple bunny example public class LittleBunny implements Bunnies private int x, y; private int carrots; public LittleBunny() x = 5; y = 5; carrots = 10; public void movebunny(int direction) if (direction == 12) y = y + 1; carrots = carrots - 1; 47

A simple bunny example else if (direction == 3) x = x + 1; carrots = carrots - 1; else if (direction == 6) y = y - 1; carrots = carrots - 1; else if (direction == 9) x = x - 1; carrots = carrots - 1; else System.out.println("Invalid direction"); 48

Interface caution Can t construct interface Can only construct objects that belong to some class 49