1 advanced classes starring: tic-tac-toe co-starring: student grades generic compareto elevator...

133
1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

Upload: justin-alexander

Post on 01-Jan-2016

219 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

1

Advanced Classes

Starring: Tic-Tac-Toe

Co-Starring: Student Grades

Generic CompareTo

Elevator Series

Page 2: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

2

Purpose: Continue our examination of OO concepts as

they relate to classes.

Our focus on the design concepts will allow us to build projects that rely on several layers of specific purpose classes that can be used to build a systems solution.

The AP requires students to be well versed in the fundamentals of OO and class construction BUT they also require a higher level ability to design a systems solution that is based on a “network” of user defined and pre-built classes.

Page 3: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

3

Resources: Deitel & Deitel “Java How to Program” 5th ED

Chapter 6 p.216, 8 p.341, 9 p.400, 10 p.437

Horstman “Java Essentials”Chapter 2 p.34, 7 p.281, 9 p.363, 11 p.429, 16 p.615

Horstman / Trees “Java Essentials Study Guide”Chapter 3 p.17, 7 p.93, 9 p.121 , 10 p.137, 13 p.207

Litvin “Java Methods” Chapter 17 Lambert “Java Comprehensive”

Lesson 9 p.269 Horstman “Big Java”

Chapter 2 p.33, 7 p.281, 9 p.363, 11 p.429 ObjectDraw Elevator Series --- Nevelle Workshop

Deitel & Deitel Elevator Series App D,E,F & prev Edition App F p.1256)

TTT --- Taft Wkshop 03

Page 4: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

4

Resources:BARRONS:

Chapter 2 & Do M/C p.49 #1-23

Chapter 3 & Do M/C p.86 #1-26

Chapter 4 & Do M/C p.120 #1-25

Chapter 5 & Do M/C p.156 #1-15 &

20-28

Page 5: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

5

Intro: In Our Lecture, last year, on the Numeric Class we

discussed many important class concepts. A list of these topics is as follows:

Final classFinal methodStatic class membersAbstract classExtendsSuper ClassSub ClassImplements --- Generic and Common Versions

Overloading methodsOverriding methodsprivate vs protected

Page 6: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

6

In addition, we created several projects that followed up and reinforced these concepts. Projects like the shape class, MoneyPenny and Employee class. At this point you should be able to Identify in code and explain all “Concepts” covered. Read, understand, evaluate and interpret programs that deal with:

abstract classesinherited classesclasses that implement interfacescontains static attributes and methodsoverloads and overrides classes

Page 7: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

7

If you are not comfortable with this skill level, you need to review previous material, read up on these concepts in your Barrons book, look at past projects and test your understanding by implementing a project that utilizes these concepts.

The AP exam will assume you have mastered OO and classes.

In this section we will cover additional concepts with regards to classes.

Page 8: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

8

At the end of this section, you will be ready to get into the core AP topics such as Recursion, Big-O, Lists, Sets, Maps, Iterators, Arraylists, ADT’s and their implementations (linked lists, binary trees, hashing, queues, stacks, PQ’s).

Page 9: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

9

Topics we will cover in this section:

Systems as a way of designing a set of interacting classes

Cohesion Coupling is a , has a Access Control Pre and Post Conditions Class Invariants Calling other Constructors Interface as an Argument Implementing a Generic (TYPED) version of

CompareTo Class Casting Converting from Subclass to Superclass without

Casting

Page 10: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

10

Super Null Reference This More with Overriding equals, ==, compareTo (primitives and

objects) Random Number Generation (Math and

Random class) Software Design (Development Lifecycle) Tic-Tac-Toe Continued Elevator Series Coding TidBit: ACSII

Page 11: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

11

TPS: Tic-Tac-Toe

(See Handout)

Page 12: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

12

Systems as a way of designing a set of interacting classes & Cohesion and Coupling:

Remember that Classes are representations of a specific, well defined CONCEPT that will interact as part of a larger System.

Page 13: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

13

For example, the Random class is an entity that has a narrow scope, it renders random numbers. It does not calculate the National Debt, answer your cell phone or bake a blueberry pie. It has a narrowly defined scope.

Page 14: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

14

Note that this class returns numbers and does not care HOW you use it. There is no I/O in this class, that is left up to another class or Driver program (SPVM).

Page 15: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

15

Classes are thought of as nouns and its behaviors (methods) are the verbs

Page 16: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

16

What are some of the classes you have created so far ?

What is their specified purpose ?

Has everything surrounding, but not specifically within , that purpose been ABSTRACTED OUT of the class ?

What classes are there in the MBS and what is their specific purpose ?

Page 17: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

17

The String, StringTokenizer, EasyReader and EasyWriter classes are other examples

A good test to determine if a class is not well defined is the class name. If the name of the class does not clearly identify the purpose of the class, then it probably is not well defined.

Page 18: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

18

If, for example you were asked to write a program that performs STUDENT GRADE calculations and SCHOOL evaluations, a class called Student would be too vague.

Cohesion & Coupling can be used to help determine the quality of the public interface of a class.

Page 19: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

19

The public methods (plus any constants) that a class exposes must be COHESIVE. All of the public behaviors must be tied to the narrow purpose of the class as it is defined. If you have behaviors that refer to multiple concepts then you may need to further decompose your class to create several, smaller, classes.

Example (from Cay Horstman):

Page 20: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

20

public class Purse({

public Purse ( ){

// constructor code}public void addNickle(int i) { // code here }public void addDime(int i) { // code here }public void addQuarter(int i) { // code here }public static final double NICKLE_VALUE = .05;public static final double DIME_VALUE = .10;public static final double QUARTER_VALUE = .25;

} First, what are the attributes defined and how are they

used ?

Page 21: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

21

This class is really combining TWO concepts here, the purse that holds the coins and the coins actual values

Since you have two concepts, decompose them into two separate concepts (entity) or classes

public class Coin{

public Coin(double value, String name) { // code here }public double getValue( ) { // code here }

}public class Purse({

private Coin myCoin;public Purse ( ){

// constructor code}public void add(Coin ci) { // code here }public double getTotal( ) { // code here }

}

Page 22: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

22

In this solution the Purse class is left to do what it does best, hold and count coins. It does not worry about the types and value of the coins, it leaves that to the Coin class.

Furthermore, the coin class can be used in other places and the purse is not limited to holding only nickels, dimes and quarters.

The Purse had the coin value and type ABSTRACTED and placed in the Coin class. Where the coins are held and what is done with them was ABSTRACTED from the Coin class.

The Purse now depends on the Coin class.

Page 23: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

23

UML View of the classes (Grady Booch) CLASS HIERARCHY:

COIN CLASS

Dependency (Purse is Dependant on the Coin Class)

PURSE CLASS

Page 24: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

24

If , in a project, you have many interdependent classes, then you have a high degree of coupling

Also, few interdependent class results in a low degree of coupling

What is preferable and Why ?

Page 25: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

25

Author Cay Horstman claims high coupling is not a good design, Horstman believes you do maximize cohesion and remove unnecessary coupling, Do you Agree ?

There is also the consideration of consistency. Follow consistent naming conventions for method names, attributes and parameters

Page 26: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

26

Java does not always provide for such consistency, can you identify any ?

Page 27: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

27

Java does not always provide for such consistency, can you identify any ?

Java’s input dialog method JOptionPane.showInputDialog(promptstring);

Java’s show message methodJOptionPane.showMessageDialog(null, messageSring);

showMessageDialog requires the parent window as the first parameter or NULL is none exists

There is no reason for this inconsistency as these methods should require the same argument string.

Page 28: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

28

IS A & HAS A:

In the previous example we can say that the Purse class HAS A Coin (class) as there is an instance of the Coin class as a class level Attribute of the Purse class

Page 29: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

29

If we were to extend (inherit from the Purse class)

public Class MensPurse extends Purse

{

// class stuff here

}

We would say that MensPurse IS A Purse

Given the following Diagram, determine the IS A and HAS A relationships:

Page 30: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

30

Object

Date DateList

Employee

Executive Maintenance

Page 31: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

31

We can say that Executive IS AN Employee

We can say that DateList HAS A Date

Object

Date DateList

Employee

Executive Maintenance

Page 32: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

32

Access Control:Classes should keep their state ( class

level attributes) private, provide for a window into the state of attributes by way of accessor methods, and allow for restricted modification of the state of some attributes by way of mutator methods.

Our access levels are Public, Private and Protected there is also Package Level access, which is outside of the scope of AP, this is the default access

Page 33: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

33

Not all attributes should be exposed to be modified.

A class with NO way to modify the initial state of a class is said to be immutable.

Do you know of any such classes ?

Side Effects: a situation where a class method modifies an attribute OUTSIDE of the implicit scope of the method.

This occurs when there is ANY type of behavior that occurs outside of the implicit scope of the object.

Page 34: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

34

For Example (from Cay Horstman):public class BankAccount

{public void transfer(double amount,

BankAccount other){

balance += amount;other.balance -= amount;

}}

First of all, what is happening here & is it legal ?

Page 35: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

35

The answer is the second argument being passed is a copy of a REFERENCE to an existing instance of the BankAccount class (an object of type BankAccount).

This method is not only updating “this” BankAccount object, it is also updating the state of the “other” object being passed !!!

How can this occur without calling a mutator method like:

other.setBalance = amount;

Page 36: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

36

Isn’t the amount attribute PRIVATE ?

Page 37: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

37

Yes it is, but when one instance of a given class has a reference to another instance OF THE SAME CLASS they implicitly have access to their private attributes as well !!!

This seems to break the concept of encapsulation, but that’s the way Java works.

So, this is a legal, although misleading move and is NOT a recommended SIDE EFFECT

Page 38: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

38

Another Example (from Cay Horstman) In SPVM we would display an accounts balance

by:System.out.println(“your balance is “ + myobj.getBalance( ) );

Why wouldn’t we do this instead (in the class itself) ?

public void printBalance( ){System.out.println(“your balance is “ +

balance );}

Page 39: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

39

This method forces this class to be COUPLED with the system class, assumes the client is in English, and has the class take on more than its narrow scope, I/O

We should try to minimize side effects within our classes accessor methods don’t change STATE & mutator methods don’t change the STATE of any object being passed as a parameter

Page 40: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

40

Remember that all parameters passed to a method are passed as COPIES (by value)

Primitives are passed as a copy so they, in effect, become local variables within the method and there scope is within that method

Page 41: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

41

Objects have their reference passed as a copy so the called method has indirect access to the actual STATE of the object being passed. While the REFERENCE parameter is local to the method, it references an object whose scope is within the calling code. Therefore, any changes to the STATE, assuming the object is mutable, is in effect being made to the source object.

Page 42: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

42

However, if we were to do the following:public class BankAccount

{public void transfer(double amount, BankAccount other)

{balance -= amount;other = new BankAcount(balance);

}}

This method is reassigning the placeholder for an instance of the BankAccount class with a new location in memory. Since the parameter other is a COPY of the reference location, this code merely reassigns the “local” copy, leaving the source object unchanged.

Page 43: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

43

Pre and Post Conditions: Precondition is a REQUIREMENT that the user of a

method must respect. If the precondition is not met then the method itself can not be responsible for any unpredictable results (including exception errors)

// PRECONDITION: The age passed will be NON negative and will be less than 120

public void setAge(int a){

age = a;}

It is a handshake agreement, much like documentation on the implementation of methods of INTERFACRES, between the class and the user of the class.

Page 44: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

44

Preconditions are used to limit parameter values OR to restrict the calling of a method to when it is an acceptable STATE

You may also set up exception errors, which we cover in detail in a later lesson, to handle inappropriate parameter values

Example:// PRECONDITION: The age passed will be

NON // negative and will be less than 120public void setAge(int a){

if (a < 0 || a >= 120)throw new IllegalArgumentException( );

age = a;}

Page 45: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

45

If the calling program executedmyClass.setAge(-10);

The following would occur:

java.lang.IllegalArgumentException at AgeClass.setAge(AgeClass.java: 21)

Page 46: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

46

Why can’ we just do the following ?

// PRECONDITION: The age passed will be NON negative and will be less than 120

public void setAge(int a)

{

if (a < 0 || a >= 120)

return;

age = a;

}

Page 47: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

47

Postcondition makes a promise that, as long as any preconditions are satisfied, the method will return a correctly calculated value, or will return control with the state of an object correctly set.

For example, a postcondition for setAge could be:

//POSTCONDITION 0 > age < 120

You can think of these conditions as a contract between the method and the user of the method( the client)

Page 48: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

48

Class Invariants:Invariants are conditions that are true and

will remain so for the duration of some action.

A loop invariant, if stated, is true when a loop initiates and will remain true throughout the execution of the loop. The invariant is true when the loop exits.

Page 49: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

49

Class Invariants:Class Invariants are similar

A class Invariant is a statement that is true about an object from its initial instantiation until it is destroyed. No method may violate or nullify this invariant

Example:

Page 50: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

50

public class AgeClass{

// PRECONDITION: age > 0 public AgeCLASS( //some arguments){}// PRECONDITION: The age passed will be NON // negative and will be less than 120public void setAge(int a){

if (a < 0 || a >= 120)throw new IllegalArgumentException( );

age = a;}

} We can reason that a Class Invariant is that

getAge( ) >= 0

Page 51: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

51

Calling other Constructors: Consider the Coin classpublic class Coin{

public Coin(double value, String name) {

myValue = value;myName = name;

}public Coin( ){

this(1, “dollar”);}

}

Page 52: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

52

Calling other Constructors: Consider the Coin classpublic class Coin{

public Coin(double value, String name) {

myValue = value;myName = name;

}public Coin( ){

this(1, “dollar”);}

} The default constructor makes a request to call another

constructor of THIS class and pass 2 arguments As long as there is such an overloaded constructor it

will be called

Page 53: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

53

Interface as an Argument: Lets modify the Purse class to allow us to get the value

of the Largest coin in the purse

public class Coin{

public Coin(double value, String name) {

myValue = value;myName = name;

}public Coin( ){

this(1, “dollar”);} public double getValue( ) { return myValue; }

}

Page 54: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

54

public class Purse({

private double sum;private int count = 0;private Coin max;public Purse ( ){

// constructor code}public void add(Coin ci) {

// code here if (count == 0 || max.getValue( ) < ci.getValue( ) ){

max = ci;}count++;sum += ci.getValue();

}public double getTotal( ) { // code here }public Coin getMax( );{

return max;}

}

Page 55: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

55

We can agree that the “mechanics” of evaluating the “maximum” value of ANY OBJECT would be the same REGARDLESS of the type of Object we were discussing.

If our Purse were to hold bills, money orders, travelers checks or any other ENTITY that can be evaluated

What would we need to do ?

Page 56: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

56

We could simply create more classes, one for each type of object that can go into a Purse

We could Abstract out common attributes and behaviors and create an Abstract class that can be extended from to handle Coins, bills, etc

Page 57: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

57

What about other objects that may require an analysis of their data, such as bank accounts or a collection of trading cards

What if we can agree on a common method, getTop , that will return whatever is the basic measure for any given object, like the current balance for a bank account or the most valuable card in your collection.

Page 58: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

58

We can build a simple INTERFACE like the following:

public interface Top

{

double getTop( );

}

As an interface, you only have the method signature, no code implementation

Page 59: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

59

You will also have the interface documented so that any user of this interface knows how it is INTENDED to be used

Our rule here is that it returns the TOTAL Numeric value, as a double, from ANY instance of the Class that implements this interface

Page 60: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

60

Remember that with interfaces: all its methods are ABSTRACT all its methods are PUBLIC they have no instance variables

Lets put this all together

Page 61: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

61

/* SuperObject refers to the Abstract class we would design

we may implement Top at the super level instead of at each

child or sub class

SuperObject is defined in SampleCode.java handout*/

Page 62: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

62

public class Coin extends SuperObject implements Top{

private static int numCoins = 0;

public Coin(double value, String name) {

setMyValue(value);setMyName(name);numCoins++;

}

public Coin( ){

this(1, "dollar"); // calls Coins constructor that takes 2 arguments}

public double getTop( ) { return getMyValue(); }

public int getNum(){

return numCoins;}

}

Page 63: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

63

In order to implement an Interface, we need to code behaviors for ALL of its methods

NOW, and this is an important concept, you can use INTERFACES as parameters and you can request to execute INTERFACE methods !!!

This, on the surface seems wrong, because an interface is nothing “alive”

We know we can pass the generic Object as an argument and then as long as we are passing a class that is underneath the Object hierarchy (and all Java objects are) then we can resolve the object at run time.

Page 64: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

64

We can also name as an argument or variable the name of an (ABSTRACT) superclass and then resolve the actual sub class at runtime.

We know this because we did this last year with the SHAPE and EMPLOYEE classes.

Well, the concept of Late or Dynamic Binding that allows us to polymorphicly resolve the sub class at run time will allow us to resolve , at run time, the actual object that is being referenced by the INTERFACE argument or variable.

The Stipulation with Interface references is that the object MUST have implemented the Interface

Page 65: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

65

public class Purse {

private double sum;private int count = 0;private Top max;public Purse (){

// constructor code}public void add(Top ci) {

if (count == 0 || max.getTop() < ci.getTop() ){

max = ci;}count++;sum += ci.getTop();

}public double getTotal() {

return sum; }public Top getTop(){

return max;}public int getCount(){

return count;}

}

Page 66: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

66

max is a variable of type Top, it can only be valued with an object that implements the Top interface

The Purse class can now only work with classes that implement the Top interface

SPVM…

Page 67: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

67

Purse myPurse = new Purse();Top [ ] myStuff = new Top[3];myStuff [0] = new Coin(.25, "Quarter");myStuff [1] = new Coin(.10, "Quarter");// assume TravelerCheck is another child ofSuperObjectmyStuff [2] = new TravelerCheck(100.0, "TC", "American Express");

myPurse.add( myStuff[0] ); // adds .25 to purse and sets THIS Coin object as maxmyPurse.add( myStuff[1] ); // adds .10 to purse myPurse.add( myStuff[2] ); // adds 100.0 to purse and sets THIS TravelerCheck object as maxSystem.out.println("the total in the purse is " + myPurse.getTotal()); // prints out 100.35

// casting OVERRIDES precedence that would execute . before casting () so extra ( )// allows the cast to occur BEFORE the method is executedSuperObject to = ((SuperObject)myPurse.getTop());

System.out.println("the total in the purse is " + to.getMyValue()); // prints out 100.0

System.out.println("the total Objects in purse is " + myPurse.getCount()); // prints out 3

// cast the reference from Top interface to a class that implements the interface// because the method getNum is a method of Coin and TCSystem.out.println("the total COINS in purse is " + ((Coin)myStuff[0]).getNum()); // prints out 2

System.out.println("the total Travelers Checks in purse is " + ((TravelerCheck)myStuff[2]).getNum()); // prints out 1

Page 68: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

68

// test instance of SEE if stuff[1] is an instance of superclass, coin and TCif (myStuff[0] instanceof SuperObject)

{System.out.println("myStuff[0] is a SuperClass");

}if (myStuff[0] instanceof Coin)

{System.out.println("myStuff[0] is a Coin");

}if (myStuff[0] instanceof TravelerCheck)

{System.out.println("myStuff[0] is a TC");

}

}// use parents compareTo method from SuperClass// compareTo evaluates against the myValue attribute

int ct = ((SuperObject)myStuff[1]).compareTo(((SuperObject)myStuff[2]));

System.out.println(((SuperObject)myStuff[1]).getMyValue() + " Compared to " +((SuperObject)myStuff[2]).getMyValue() + " returned " + ct);

Page 69: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

69

OUTPUT:

the total in the purse is 100.35

the total in the purse is 100.0

the total Objects in purse is 3

the total COINS in purse is 2

the total Travelers Checks in purse is 1

myStuff[0] is a SuperClass

myStuff[0] is a Coin

Page 70: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

70

At run time, the actual type of object being held in the Purse (coins, bills, travelers checks) is resolved AND THAT SPECIFIC classes getTop behavior will get executed

Interfaces can be used as variable types and as parameter types --- but they carry a restriction that they can only be filled in with classes that implement the specified interface

Page 71: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

71

Implementing a Generic (TYPED) version of CompareTo:

Beginning with Java version 1.5 (introduced in 2006-2007), Java provides for Generic or Typed Versions of its implementations of ADT’s like Arraylists, Maps, Sets, etc.

The Comparable Interface has also been TYPED so that it can generically be implemented to handle any specific class and NOT JUST the Object class.

Page 72: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

72

A Look at the Java Doc for Comparable indicates this by the <T> in the declaration

Creating a class that is “Generic” or Typed is not a part of the AP subset, but we will address the topic on how to create GENERICLY typed classes

A Look at the sample Code (available ONLINE) shows BOTH the common (object based) and Generic Ways to implement CompareTo

Page 73: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

73

// Make Use of Java 1.5's Generic use of compareTo where we// can TYPE the compareTo method to accept a specific class

(or // any in its hierarchy) public int compareTo(SuperObject o) throws ClassCastException// Non Generic Version of CompareTo:// public int compareTo(Object o) throws ClassCastException

{//if (this.myValue < ((SuperObject)o).myValue)

if (this.myValue < o.myValue){

return -1;}

//if (this.myValue > ((SuperObject)o).myValue) if (this.myValue > o.myValue)

{return 1;

}

return 0; // equal}

Page 74: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

74

Now we can access this method in the Driver as follows:

// use parents compareTo method from // SuperClass

// compareTo evaluates against the myValue //attribute

int ct = ((SuperObject)myStuff[1]).

compareTo(((SuperObject)myStuff[2]));

Page 75: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

75

We Still need to cast as the compareTo is implemented on the parent level, however, if the compareTo was implemented on the child level, then no casting would be necessary

Page 76: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

76

In the common version of CompareTo, the implementation in the SuperObject would have to cast the object being passed into a SuperObject BEFORE invoking any of its methods

In the Generic version of CompareTo, the argument being passed is already known as a SuperObject, therefore the casting in not needed making the code much simpler

Page 77: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

77

Class Casting: We have discussed casting with primitives as

well as some casting with regards to classes We looked at Java’s String class code and saw

that they had several methods accept the Object class as an argument and then evaluated the argument passed by using the instanceOf ( ) method and then casting the Object to the String class

We also used casting in our Shapes and Employee projects where we implemented the Comparable interface

myPurse.add( myStuff[0] );

Page 78: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

78

This code passes an Object of type Coin to the add method of the Purse class even though the add method’s parameter is of type Top (an interface)

In Java we can convert from an Interface as long as the actual object being passed at runtime implements that interface

Page 79: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

79

However, we can not do the following:

Top myT ; // OK

myT = new Coin(0.5 , “Nickle”); //OK// myT is now “filled in” with an instance

of // coinString type = myT.getName( ); // NOT OK// because, although, myT refers to a coin,

it // is still defined as a Top interface SO // only the methods defined in the // interface can be executed

Page 80: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

80

We can NOT do this because , although we know it refers to a Coin object, the compiler does not

Therefore the compiler sees that the myT type has no getName method

So as long as we know myT refers to a Coin, we can do the following:

Coin c = ( Coin) myT; Then we can say:

String type = c.getName( );

Page 81: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

81

We could shorthand things

String type = ( ( Coin ) myT ) . getName( );

This works because the parentheses override the natural order of operations

Java access class feature ( . ) has a higher precedence than the cast operator

So if we said

String type = ( Coin ) myT . getName( );

Page 82: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

82

Then the compiler checks to see if getName is a method of c BEFORE c can be cast to the type Coin !!!

See Handout on Order of Precedence

If the object c does not have the appropriate interface then a runtime exception error will be thrown

Of course you can use instanceof to test the object

Page 83: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

83

if (myT instanceof Coin)

{

Coin c = ( Coin) myT;

}If True, then c is of type Coin

Page 84: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

84

The Super Keyword:Consider the class Athlete

Athlete’s have a name and a sport, keep track of hours trained for their sport, participate in only 1 sport, different sports require different training methods

We have the following structure:

Page 85: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

85

Flier (Interface)

fly( )

Athlete

namesporthoursTraining

getName( )getSport( )train( )getHoursTraining( )SkiJumper

numberOfJumpsgetJumps( )fly( )train( )

Page 86: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

86

We see that SkiJumper IS A Athlete and also implements the Flier Interface

Can you write the basic structure of based on this diagram ?

Explain the relationships illustrated in this diagram

Add a box for a RunnerRunner keeps number of races, miles

raced and has a race behaviorHow is the Train behavior handled for the

Runner ?

Page 87: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

87

Here is a part of the SkiJumper class:

class SkiJumper exends Athlete implements Flier

{

public SkiJumper(String n, String s, Double ht )

{

super( n, s, ht);

numberOfJumps = 0;

}

}

Page 88: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

88

To call the parents constructor IT MUST BE THE FIRST STATEMENT in the childs constructor !!!

If the child does not call the parent’s constructor then the parents DEFAULT constructor is called

Page 89: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

89

If the parent has NO default constructor, then a Compiler Error will occur !!!

“super” can also be used to invoke a parent’s method from a child by affixing the appropriate method

Page 90: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

90

Even though SKiJumper and Runner INHERIT from Athlete, they do not have direct access to the PRIVATE class level attributes of their parent

Given that the parent’s train( ) method updates the hoursTraining attribute

How then can the sub classes access and or modify these attributes ?

Page 91: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

91

We can make the Athlete’s private attributes Protected

We can call the parent’s public method that modifies the private attributes

Page 92: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

92

class SkiJumper exends Athlete implements Flier

{

// constructor and other code

public void train(double hours)

{

// does some class specific work

super.train(hours); // then call parent’s //version of the method train( )

}

}

Page 93: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

93

SkiJumper’s train( ) method OVERRIDES the athlete’s train( ) method, but the parent’s method, as well as any other public parent method can be called with the super keyword

Lets say we now want the ability to compare SkiJumpers based on their number of jumps, how can we do this ?

Page 94: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

94

We can implement the Comparable interface class

SkiJumper extends Athlete implements Flier, Comparable

Remember that although we can only extend from one class we can implement MANY interfaces

Page 95: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

95

public int compareTo( Object o){

SkiJumper temp = (SkiJumper) o;if(this.numberOfJumps < temp.numberofJumps) // ** use class // attribute directly

return -1; if(this.getJumps ( ) > temp.getJumps( ) ) // use the accessor methods

return 1;return 0;

}

Page 96: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

96

** Remember that we can directly access the private attributes of the class being passed to this method because the object is also of type SkiJumper and 2 instances of the same class can access each other’s

private attributes

Page 97: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

97

Now, we make the following declarations:

SkiJumper j1 = new SkiJumper(“Eric”, “Nash”);

SkiJumper j2 = new SkiJumper(“Steve”, “Mash”);

Athlete j3 = new SkiJumper(“Mike”, “Hash”);

Runner r1 = new Runner(“Chris”, “Rash”); We can do the following:

if (j1.compareTo(j2) > 0)

// do stuff

if (j2.compareTo(j1) > 0)

// do stuff

if (j1.compareTo(j3) > 0)

// do stuff

Page 98: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

98

The following will NOT compile:

if (j3.compareTo(j1) > 0)

Because j3 IS AN Athlete and compareTo( ) is NOT defined in the Athlete class

Page 99: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

99

Where a parent reference valued with a child has the restriction similar to an interface reference where that reference can only be used to invoke methods that are KNOWN to the parent

Looking at our Purse and Coin Classes…Therefore the following will cause an error as we

have a reference of type SuperObject and fill it in with TravelerCheck child

And Then we attempt to call the getCheckType() method of the child a compiler error will occur

Page 100: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

100

SuperObject s;

s = new TravelerCheck();

s.getCheckType(); // this method is NOT in SuperObject

s = new TravelerCheck();

((TravelerCheck)s).getCheckType();

// This will work as we can cast down from parent to a child

Page 101: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

101

Further, using the Athlete classes:

if (j1.compareTo(r1) > 0)

Compiles but throws a ClassCastException because the compareTo( ) method of SkiJumper class tries to cast Runner to a SkiJumper and a Runner IS NOT a SkiJumper !

Page 102: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

102

What happens with:

j3.fly( );

r1.fly( );

Page 103: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

103

Compile errors result because the fly( ) method is NOT defined for Athlete or for Runner

Page 104: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

104

What happens here:

j3.train(21);

Page 105: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

105

What happens here:

j3.train(21);

The train method is defined for an Athlete However the method is overridden in the SkiJumper class

Page 106: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

106

The SkiJumper method is invoked because, even though the reference is Athlete , the ACTUAL object instantiated (filling in the generic Athlete reference holder) is of type SkiJumper and it always that object’s methods that get invoked first.

Converting from Subclass to Superclass without Casting:

j3 = j1;

Page 107: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

107

Is valid because SkiJumper IS AN Athlete (a subclass of Athlete) AND an object of a SUBCLASS can be assigned to an object of its SUPERCLASS without requiring and casting

j1 = j3;Will not compile as an explicit cast is

required as an object of a SUPERCLASS can be assigned to an object of its SUBCLSSS as long as it is appropriately CAST

Page 108: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

108

j1 = (SkiJumper)j3;is valid !!

Page 109: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

109

This:By the Way. what is with this as used in

the previous example?Every object can access a reference to

itself with the keyword thisIn a method, the THIS reference can be

used implicitly or explicitly to refer to instance variables and methods of the object on which the method was called.

Recall the compareTo method in SkiJumper:

Page 110: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

110

public int compareTo( Object o){

SkiJumper temp = (SkiJumper) o;if(this.numberOfJumps < temp.numberofJumps( ) ) // ** use class // attribute directly

return -1; if(this.getJumps > temp.getJumps( ) ) // use the accessor methods

return 1;return 0;

}

Page 111: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

111

the keyword “this” is implicit and therefore does not need to be coded

It does highlight that the comparison being performed is on the current object and is evaluating this current object against one passed in

SPVM…

Page 112: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

112

SkiJumper sk1 = new SkiJumper((“Eric”, “Nash”);

SkiJumper sk2 = new SkiJumper((“Eric”, “Nash”);

sk1.compareTo(sk2);In this example the object sk1 is

requesting the compareTo, so the “this” in the call refers to the STATE of sk1

sk2 is the argument “o”

Page 113: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

113

Null Reference:When variables of an object are declared,

a placeholder is reserved that will hold the memory address where the actual STATE of that object is maintained

String myString;

At this point, there is no actual reference to any STATE for this object

Page 114: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

114

If we were to try and execute a method on this empty reference we would get a NullObjectReference error

myString.length();

In this case we have a null object

You can perform a check to ensure the object has been instantiated

if (myString == null)

Page 115: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

115

More with Overriding:

In the Athlete example we saw another example of method overriding

In a Super / Sub relationship you inherit the public & protected methods and attributes. Also, you may have access to the parent’s private attributes if there are public accessor methods

Page 116: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

116

When you inherit from a class the child may write its own behavior for a parents public method

Page 117: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

117

When that occurs and an object of that child is instantiated, it is the child method’s behavior that gets executed --- provides polymorphism

If you wish to execute the parent’s behavior you need to explicitly call the parent’s method by using the super keyword.

Add the following o the Athlete class:

Page 118: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

118

public String toString ( ) // parents toString // method

{return (name + “ is training for “ + sport ); // this.name this.sport

} Add to SkiJumper:public String toString ( ) // the overridden

method // for the child class{

String s = super.toString();return (s + “ and jumped “+ numberOfJumps + “ times” ); // this.name this.sport

}

Page 119: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

119

Equals , ==, compareTo:

The equals( ) method is used to compare the state of object instances

== compares the actual variable declarations. If they are two objects then == compares their REFERENCE values in memory. If they are two primitives they compare the actual values in those variables.

compareTo is an implementation of the Comparable interface and can be used to evaluate any object that implement this interface.

Page 120: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

120

Random Number Generation (Math and Random class)

There are two classes that provide for random numbers

java.util.Random

With this class you need to create an instance of the class first by invoking the default or seeded constructor

Random myRand = new Random(21);int IRnd = myRand.nextInt( );

Page 121: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

121

There are other methods to return Boolean, double and long

java.lang.Math has a random() methodReturns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

Page 122: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

122

Since this is a static method, you do not instantiate anything

You simply reference the class name to obtain a random number

double dRand = Math.random( );

Page 123: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

123

Software Design (Development Lifecycle):

AP Students are required to: Understand Encapsulation Understand the is-a has-a relationship Implement an Inheritance class hierarchy according to

given specifications Design and implement a class given specifications Understand when o use an Interface and be able to

design an Interface Extend a given class with Inheritance Discover and Design classes Determine relationships between classes Determine responsibilities of each class Use OO design to build a program from a set of

interacting classes

Page 124: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

124

Development Life Cycle:Analysis “What is the problem that we

are attempting to resolve”

Design “How can we translate a solutions into a system’s implementation”

Implementation “Breath life into the system design, reevaluate and modify”

Page 125: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

125

Testing

“Ongoing unit testing and reevaluation of the design and implementation”

“End to end testing of entire system, boundry and stress testing”

“User acceptance testing, run parallel systems”

Page 126: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

126

Deployment

“Distribute system, go live”

“Based on scope of system, may implement in phases”

Page 127: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

127

When you enter the Design phase, you need to identify the “entities” that are required

Make sure the scope of these entities are clearly defined (attributes and behaviors)

What are the “entities” of our Tic-Tac-Toe program ?

What are the “entities” of our Student Grades program ?

What are the “entities” of a Banking Transaction program ?

Page 128: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

128

Entities become classes during the Implementation stage

Examine the classes and their interrelationships Are there any common elements between

classes where a hierarchy can work, will an abstract or concrete Super class work ? These are IS-A relationships

Are there any classes that are dependant on other classes ? These are HAS-A relationships

These dependencies exist in cases where classes are used as attributes of other classes

Page 129: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

129

Examples: A Car IS-A Vehicle A MotorCycle IS-A Vehicle A Car HAS-A Tire A Car HAS-A Navigation Device A Purse HAS-A Coin A Coin IS-A SuperClass A HumanPlayer IS-A Player A ComputerPlayer IS-A Player A Player HAS-A Move A Move HAS-A GameBoard A Bank HAS-A Customer A Customer HAS-A BankAccount A SavingsAccount IS—A BankAccount

Page 130: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

130

When there is a lot of dependencies there is High Coupling

As you define your classes, identify their responsibilities and develop them into a set of behaviors and required attributes

Make sure you ABSTRACT out behaviors and attributes that ARE NOT within the scope of the class

Make a list, Draw a UML like Diagram to identify your classes and their responsibilities as well as the other classes on which this class depends

Page 131: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

131

Coding TidBit: ASCII

int n = (int) ‘e’ - (int) ‘a’;

// gives you the displacement of ‘e’ from the beginning of an array

// this can be used to count the number of letters in a phrase (an array of 26 ints)

Page 132: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

132

Projects:

TTT (as a TPS) Student Grades (in class) Bank Transaction --- first step list classes use

diagram (required) Vending Machine --- first step list classes use

diagram (required)

Elevator Series (Part 2) Bubble Sort --- add ability to sort by ascending

OR descending order --- add ability to identify

DUPLICATE or EQUAL elements and the number of times this occurs

Page 133: 1 Advanced Classes Starring: Tic-Tac-Toe Co-Starring: Student Grades Generic CompareTo Elevator Series

133

TEST FOLLOWS THE PROJECT DUE

DATE !!!