44
CPSC 111 Introduction to Computation November 24 th , 2009 Based on slides by Eiselt, Carter, Murphy, Pottinger

CPSC 111 Introduction to Computation November 24 th, 2009 Based on slides by Eiselt, Carter, Murphy, Pottinger

  • View
    216

  • Download
    0

Embed Size (px)

Citation preview

CPSC 111Introduction to Computation

November 24th , 2009

Based on slides by Eiselt, Carter, Murphy, Pottinger

Administrative Stuff

• On-line system for submitting your teaching evaluations is open– https://eval.olt.ubc.ca/science.– You should have received email about it– Open until Dec. 6

• We really value your feedback, it can make a difference in improving our teaching!

Administrative Stuff

• Midterms are being distributed during this week’s labs

Administrative Stuff Big reading in Big Java 3rd edition:

Chapter 1.1 through 1.8 (introduction)Chapter 2.1 through 2.10 (using objects)Chapter 3.1 through 3.8 (implementing classes)Chapter 4 (data types)Chapter 5.1 through 5.4 (decisions)Chapter 6.1 through 6.5 (iteration)Chapter 7.1, 7.5, 7.6, 7.7 (arrays)Chapter 14.1, 14.3 (searching and sorting)Chapter 8.1 through 8.9 (designing classes)Chapter 9.1, 9.2, 9.3 (interfaces and polymorphism)Chapter 10 (inheritance)Chapter 2.11, 2.12 (simple graphics)Chapter 9.5, 9.6, 9.7, 9.8, 10.9, 10.10 (event handling

and graphical user interfaces)

Administrative Stuff Big reading in Big Java 2nd edition:

Chapter 1.1 through 1.8 (introduction)Chapter 2.1 through 2.10 (using objects)Chapter 3.1 through 3.8 (implementing classes)Chapter 4 (data types)Chapter 6.1 through 6.4 (decisions)Chapter 7.1 through 7.5 (iteration)Chapter 8.1, 8.5, 8.6, 8.7 (arrays)Chapter 19.1, 19.3 (searching and sorting)Chapter 9.1 through 9.9 (designing classes)Chapter11.1, 11.2, 11.3 (interfaces and polymorphism)Chapter 13 (inheritance)Chapter 5.1, 5.2 (simple graphics)Chapter 11.5, 12.1, 12.2, 12.3 (event handling

and graphical user interfaces)

So where are we?• We learned

– programming language basics– about classes– about conditionals (if statements)– about loops– about arrays– Sorting and searching efficiently

• And are learning– Inheritance (one OOP way to reuse code)– Interfaces (another OOP way to reuse code)– Polymorphism: method overriding and method overloading

• Next we will look at– Abstract classes

OOP is reuse

OOP lets us reuse a class definition to create lots of instances (objects) of that class.

Inheritance: lets us reuse class definitions to help with the creation of new, related but different class definitions

Interfaces: let us use incomplete class definitions to help with the creation of other class definitions

interface

class class

classparent:

child:

implements extends

On the left, the parent interface serves as a specification for the child class.

It tells Java what methods must be defined, and what the parameter lists must look like, before a class can be said to implement the interface.

It does not tell Java what the methods must do or how they must do it.

It only tells Java how the "outside world" interacts with objects of that class.

To Summarize…

On the right, the parent class tells Java what methods and variables will be included in objects derived from the child class.

This is lots more information than is provided by the interface, so the programmer has less to do when defining the child class.

But the programmer may want to change the way the methods inherited by the child class behave, and that means some of the work comes back anyway.

interface

class class

classparent:

child:

implements extends

To Summarize…

In both cases, the parent prescribes "minimums" for the child.

The child class definition isn't limited to what's shown in the parent

-- in both cases we can add more variables and more methods to the child classes than what's prescribed by the parents.

interface

class class

classparent:

child:

implements extends

Interfaces and inheritance are two ways to provide organizational structure to a collection of classes.

Hierarchies

That organizational structure is a hierarchy.

Why do we care about organization?

Because when programs get real (where real == big), a well-organized program will make your programming life easier. Like when you're making a completely computer-generated feature-length film about dancing penguins.

What do these relationships look like?

Ride

RollerCoaster2008

WaterRide2008

KiddieRide2008

ThrillRide2008

implements implements

EvenCoolerRollerCoaster

extends

Method overriding

Java allows a child class to define a method with the same name and signature as a method in the parent class,

The method definition in the child class is the one that Java uses when that method is called on an object of that class

In this case, we say that the child's version overrides the parent's version in favor of its own.

Method overridingpublic class ThemeParkAgain{ public static void main (String[] args){ RollerCoaster [] mys = new RollerCoaster[5]; mys[0] = new RollerCoaster(32); mys[1] = new ShinyRollerCoaster(23); mys[2] = new ExtraShinyRollerCoaster(2); for (int i = 0; i < mys.length; i++){ if (mys[i] != null){ System.out.println(mys[i].getAdvertisingCopy()); } } }}> java ThemeParkAgainAnother ride is ready to go!Another ride is ready to go!Another ride is ready to go!Go up and down and round and round!Go upside-down for maximum thrills!More fun than a barrel of monkeys!

Method overloadingJava also 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.

It is called method overloading.

It's what enables System.out.println() to accommodate different types of parameters...

Method overloadingWhen two or more methods in the same class 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, combined with the 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.

Method overloading - different typespublic 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!"); }}

We want this method to print, depending on the type of the parameter-“I am a <type of the parameter>”

Method overloading - param list lengthpublic 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(int a, int b) { return ((a + b) / 2.0); } public static double avg(int a, int b, int c) { return ((a + b + c) / 3.0); }}

We want this method to return the average of the parameters

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

1 error found:Error: avg(int,int) is already defined in AvgTest2

Method overloadingWhen two or more methods in the same class 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.

If you try to create two methods with the same signature, the compiler will let you know.

Method overloading

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? Java can't know from the method invocation which method was intended to be used, and it's not going to choose one at random, is it?

Method overloadingpublic 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:Error: avg(double,double) is already defined in AvgTest3Error: possible loss of precisionfound : doublerequired: float

Recap: what is polymorphism?

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 is made possible in Java through method overloading and method overriding.

from Just Java 2 by Peter van der Linden (6th edition, p. 171)

Polymorphism and method overloading

Method overloading is the "easy" kind of polymorphism. It means that in any class you can use the same name for several different (but hopefully related) methods.

The methods must have different signatures, however, so that the compiler can tell which of the different methods is intended.

Method overriding is the more "complicated" kind of polymorphism.

Some folks think of this as true polymorphism.

It occurs when a subclass has a method with the same signature (number, type, and order of parameters) as a method in the superclass.

When this happens, the method in the derived class overrides the method in the superclass.

This kind of polymorphism is resolved at execution time, not at compilation time.

Polymorphism and method overriding

But there are some who say…

Method overloading is nothing more than having two methods with the same name but different argument lists. Period.

There's no polymorphism involved with overloaded methods!

from Head First Java by Kathy Sierra and Bert Bates (2nd edition, p. 191)

Huh?

Programming languages are complicated beasts, and the concepts underlying them can be challenging.

Polymorphism means different things to different people, even when the people are very experienced programmers who have authored highly-regarded Java books.

(And are those different interpretations of polymorphism surprising, given that the name itself means "many forms"?)

So where are we?• We learned

– programming language basics– about classes– about conditionals (if statements)– about loops– about arrays– Sorting and searching efficiently

• And are learning– Inheritance (one OOP way to reuse code)– Interfaces (another OOP way to reuse code)– Polymorphism: method overriding and method overloading

• Next we will look at– Abstract classes

A new wrinkle

Let's say we want to expand our Ride empire to include Water Rides.

Is a Water Ride a subclass of Roller Coaster?

If we have this...

RollerCoaster

ShinyRollerCoaster

ExtraShinyRollerCoaster

extends

extends

...does this make sense?

RollerCoaster

ShinyRollerCoaster

ExtraShinyRollerCoaster

WaterRide

extends extends

extends

Does this make more sense?

Ride

RollerCoaster

ShinyRollerCoaster

WaterRide

ExtraShinyRollerCoaster

extends

extends extends

extends

Does this make more sense?

Ride

RollerCoaster

ShinyRollerCoaster

WaterRide

ExtraShinyRollerCoaster

How can we create a generic Ride class that won't actually generate objects directly but will instead be used as a template for more specific classes that will be instantiated, like WaterRide and RollerCoaster?

One way would be to make a Ride interface, like we have already done.

Here's another way...

extends

extends extends

extends

Abstract classesAbstract classes serve as place holders in a class hierarchy.

An abstract class is typically used as a partial description that is inherited by all of its descendants.

The description is insufficient to be useful by itself, and so is not instantiated. Why is it insufficient?

Because an abstract class may contain abstract methods as well as concrete methods.

The descendant classes supply additional information so that their instantiation is meaningful.

Thus an abstract class is a generic concept in a class hierarchy.

A class becomes abstract by including the abstract modifier in the class header.

Abstract classes - another viewAn abstract class is a class that is not completely implemented.

It usually contains one or more abstract methods.

Remember? An abstract method has no definition--that is, it specifies a method that should be implemented by subclasses, but does not provide an actual implementation for that method...just the header.

Like an interface, an abstract class uses abstract methods to specify what some of the methods in the descendant classes must look like even if it's not possible to provide the implementation details for the methods that make up the interface.

For instance, if we wanted to require that all subclasses of the Ride class implement a getAdvertisingCopy() method even though that method might differ greatly between one subclass and another, we could use an abstract method.

You may ask"Why don't we just use an ordinary class for our generic template? Why do we need an abstract class?"

We need an abstract class if we want

• real (concrete) methods in our template that all descendants of these class should inherit

• but we also want some abstract methods when it doesn't make sense for the parent class to provide full, concrete definitions for them (e.g. getAdverstisingCopy()).

Abstract classes - an example

Here's an example of a simple Ride class hierarchy that begins with an abstract class. We'll provide a RollerCoaster definition and a WaterRide definition, along with a little test program.

To keep things clear, we’ll call our new WaterRides and RollerCoasters WaterRideV1 and RollerCoasterV1 (for Version 1)

Abstract classes - an example

GenericRide

RollerCoasterV1

ShinyRollerCoasterV1

WaterRideV1

Here's what our new and improved classhierarchy looks like now

extends

extends extends

ExtraShinyRollerCoasterV1

extends

Abstract classespublic abstract class GenericRide{ protected int capacity; protected int numberOfRiders; public GenericRide() { capacity = 2; numberOfRiders = 0; } public void board() { board("welcome on board","Sorry, the ride is full"); } …

Regular Methods

What’s happening here?

Abstract classes… public void board(String message1, String message2) { if (numberOfRiders < capacity) { numberOfRiders++; System.out.println(message1); } else { System.out.println(message2); }

} public abstract String getAdvertisingCopy();}

Abstract Method

Method overloading

Abstract classes

public class RollerCoasterV1 extends GenericRide{ public RollerCoasterV1() { super(); } public void board() { board("Welcome on the roller coaster","Sorry, the roller coaster is full"); } public String getAdvertisingCopy(){ return "A thrilling roller coaster!"; }}

Method overriding or overloading or neither?

Method overriding- Overrides “board()” in Generic Ride

Where does this come from?

Version of board(string, string) inherited From Generic Ride!

Implementation of abstract method in GenericRide

Abstract classes

public class ShinyRollerCoasterV1 extends RollerCoasterV1{

public ShinyRollerCoasterV1() { super(); } public void emptyCoaster() { numberOfRiders = 0; }

public String getAdvertisingCopy() { return "Go upside-down for maximum thrills!"; }}

There is no board() method here! What happens when we try to board a shyniRollerCoasterV1?

Implementation of abstract method in GenericRide

New method

Inherits the “board()” method from RollerCoasterV1

Abstract classespublic class WaterRideV1 extends GenericRide{

public WaterRideV1() { super(); } public void board() { board("Welcome on the water ride","Sorry, the water ride is full"); } public String getAdvertisingCopy(){ return "A fun drenching for everyone!"; }

}

Method overriding- Overrides “board()” in Generic Ride

From Generic Ride!

Implementation of abstract method in GenericRide

Abstract classespublic class ShinyThemeParkV3{ public static void main (String[] args){ GenericRide[] myrides = new GenericRide[5]; myrides[0] = new RollerCoasterV1(); myrides[1] = new WaterRideV1(); myrides[2] = new ShinyRollerCoasterV1(); for (int i = 0; i < myrides.length; i++){ if (myrides[i] != null){ myrides[i].board(); System.out.println(myrides[i].getAdvertisingCopy()); } } }}

> java ShinyThemeParkV3Welcome on the roller coasterA thrilling roller coaster!Welcome on the water rideA fun drenching for everyone!Welcome on the roller coasterGo upside-down for maximum thrills!

Printed from a ShinyRollerCoaster object

It used the board() method from the superclass-Roller Coaster