University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Interfaces, Polymorphism Lecture 28, Wed Mar 24 2010.

Slides:



Advertisements
Similar presentations
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Interfaces, Polymorphism Lecture 20, Tue Mar
Advertisements

University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Inheritance II Lecture 34, Mon Apr
Inheritance Inheritance Reserved word protected Reserved word super
Introduction to Object-Oriented Programming CS 21a: Introduction to Computing I First Semester,
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
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
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Parameter/Scope Review II, Inheritance Lecture 33,
Methods Liang, Chapter 4. What is a method? A method is a way of running an ‘encapsulated’ series of commands. System.out.println(“ Whazzup ”); JOptionPane.showMessageDialog(null,
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Arrays II Lecture 15, Thu Mar
CS 106 Introduction to Computer Science I 11 / 20 / 2006 Instructor: Michael Eckmann.
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 2D Arrays, Sorting Lecture 16, Tue Mar
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Enhancing classes Visibility modifiers and encapsulation revisited
CPSC 111 Introduction to Computation November 24 th, 2009 Based on slides by Eiselt, Carter, Murphy, Pottinger.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Loops III Lecture 20, Fri Mar
COMP 14 Introduction to Programming Mr. Joshua Stough February 28, 2005 Monday/Wednesday 11:00-12:15 Peabody Hall 218.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
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 More Class Design Lecture 30, Mon Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Loops III Lecture 19, Wed Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Interfaces, Polymorphism Lecture 29, Fri Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 2D Arrays, Sorting Lecture 23, Fri Mar
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 Arrays and Class Design Lecture 18, Tue Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Arrays Lecture 21, Mon Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design II Lecture 31, Wed Mar
Templates. Objectives At the conclusion of this lesson, students should be able to Explain how function templates are used Correctly create a function.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Yet More Array Practice Lecture 24, Mon Mar
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 More Class Design III, Parameter/Scope Review Lecture.
CMSC 202 Interfaces. 11/20102 Classes and Methods When a class defines its methods as public, it describes how the class user interacts with the method.
Writing Classes (Chapter 4)
Introduction to Objects A way to create our own types.
Introduction to Object-Oriented Programming
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Templates An introduction. Simple Template Functions template T max(T x, T y) { if (x > y) { return x; } else { return y; } } int main(void) { int x =
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
Agenda Object Oriented Programming Reading: Chapter 14.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Session 7 Methods Strings Constructors this Inheritance.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
1 Class 1 Lecture Topic Concepts, Definitions and Examples.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
AD Lecture #1 Object Oriented Programming Three Main Principles 1 Inheritance Encapsulation Polymorphism.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Classes - Intermediate
Methods.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Class Design II Lecture 7, Thu Jan
Programming Language Concepts (CIS 635)
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Classes, Encapsulation, Methods and Constructors (Continued)
CS2011 Introduction to Programming I Methods (II)
Winter 2019 CMPE212 5/25/2019 CMPE212 – Reminders
Corresponds with Chapter 5
Presentation transcript:

University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Interfaces, Polymorphism Lecture 28, Wed Mar borrowing from slides by Kurt Eiselt

2 News n change for labs n week 11 was no lab. now will be optional midterm review/correction n a chance to work through your mistakes and get some marks back n people with Monday (holiday) labs or conflicts can attend another lab and/or work on their own. anyone bring in corrected midterm at beginning of the week 12 lab if not finished working through during week 11 lab

3 Reading n This week: n (3rd ed) n (2nd ed)

4 Recap: Favorite Colors n record everybody's favorite color n how can we do "averages" per row? n find the max n keep array of vote counts for each color, for each row

5 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 = ; boolean c = false; String d = "woohoo!"; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); } > java PrintlnTest false woohoo!

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 = ; boolean c = false; String d = "woohoo!"; System.out.println(a); System.out.println(b); System.out.println(c); System.out.println(d); } > java PrintlnTest 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 = ; 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?

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

9 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!"); }

10 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); }

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

12 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 }

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 } 1 error found: File: AvgTest2.java [line: 13] Error: avg(double,double) is already defined in AvgTest2

14 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?

15 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

16 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++; }

17 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"); } Constructor overloading

18 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++; } Constructor overloading

19 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 Constructor overloading

20 Another vending-related opportunity Let's say that you've been inspired by CPSC 111 and decide to create commercial vending- machine 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...

21 Pizza machines...

22 Beer machines...

23...and even French fry machines!

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

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

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

27 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).

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

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

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

31 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; }

32 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 ; System.out.println("Have a Coke"); System.out.print(itemsRemaining); System.out.println(" cans remaining"); } else { System.out.println("Sold out."); }

33 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; }

34 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 ; 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."); }

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

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

37 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

38 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

39 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

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(); } 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?

41 Why this stuff is very very cool 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.... Because the alternative is to write lots of chunks of code that look like sort of like this (if they were written in English): As the number of classes within the same hierarchy grows, so does the size of the chunks of code represented above. Eeyow!

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