Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CPSC 111 Introduction to Computation November 24 th, 2009 Based on slides by Eiselt, Carter, Murphy, Pottinger."— Presentation transcript:

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

2 Administrative Stuff On-line system for submitting your teaching evaluations is open – https://eval.olt.ubc.ca/science. 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!

3 Administrative Stuff Midterms are being distributed during this week’s labs

4 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)

5 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)

6 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

7 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

8 interface class parent: 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 …

9 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 parent: child: implements extends To Summarize …

10 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 parent: child: implements extends

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

12 What do these relationships look like? Ride RollerCoaster 2008 WaterRide 2008 KiddieRide 2008 ThrillRide 2008 implements EvenCooler RollerCoaster extends

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

14 Method overriding public 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 ThemeParkAgain 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!

15 Method overloading Java 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...

16 Method overloading When 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.

17 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!"); } } We want this method to print, depending on the type of the parameter -“I am a ”

18 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(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

19 Method overloading public 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

20 Method overloading When 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.

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

22 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: Error: avg(double,double) is already defined in AvgTest3 Error: possible loss of precision found : double required: float

23 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)

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

25 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

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

27 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"?)

28 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

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

30 If we have this... Roller Coaster ShinyRoller Coaster ExtraShiny RollerCoaster extends

31 ...does this make sense? Roller Coaster ShinyRoller Coaster ExtraShiny RollerCoaster WaterRide extends

32 Does this make more sense? Ride Roller Coaster ShinyRoller Coaster WaterRide ExtraShiny RollerCoaster extends

33 Does this make more sense? Ride Roller Coaster ShinyRoller Coaster WaterRide ExtraShiny RollerCoaster 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

34 Abstract classes Abstract 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.

35 Abstract classes - another view An 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.

36 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()).

37 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)

38 Abstract classes - an example Generic Ride RollerCoaster V1 ShinyRoller CoasterV1 WaterRide V1 Here's what our new and improved class hierarchy looks like now extends ExtraShiny RollerCoasterV1 extends

39 Abstract classes public 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?

40 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

41 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

42 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

43 Abstract classes public 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

44 Abstract classes public 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 ShinyThemeParkV3 Welcome on the roller coaster A thrilling roller coaster! Welcome on the water ride A fun drenching for everyone! Welcome on the roller coaster Go upside-down for maximum thrills! Printed from a ShinyRollerCoaster object It used the board() method from the superclass-Roller Coaster


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

Similar presentations


Ads by Google