Test 2 Review

Download Report

Transcript Test 2 Review

Session 25
Test 2 Review
Test 2 Details
• Tuesday, November 22 in class
– (Anybody planning on taking it on Friday?)
• Closed book
• Closed notes, except for one 8.5” x 11”
page of notes (front and back is okay)
• Test is about half coding and half short
essay questions (similar to Test 1)
Test 2 Material
Chapter 7 -- Pinball Game
Chapter 8 -- Understanding Inheritance
Chapter 10 – Mechanisms for Software Reuse
Chapter 11 – Implications of Inheritance
Chapter 12 – Polymorphism
Slides and Handouts from Lecture
General Study Hints
1. Go through each chapter and making a
list of the vocabulary terms that we have
discussed. Could you explain what each
means and how they relate to each other?
2. Review the slides I used during class
and consider the points I have
emphasized either directly on the slides or
in addition to the slides.
Study Hints
3. Review the programs we have worked with (Pinball
Game Versions 1-3, Set example using composition,
Projectile, Pinball Pallet exercise solution, my Tic Tac
Toe solution for HW5, etc). I will provide you with any
code I expect you to use/modify, but you don’t want to
waste test time reviewing how the code actually works.
4. Read through the questions at the end of the
chapters. Play the "second guess” the instructor game.
That is, think about what you reviewed in the previous
steps and think about how well each question would fit
into these topics. Some of my questions will come from
these questions. Others will be modifications to these
questions based more on what I have chosen to
Chapter 7 Pinball Game
• Mouse Events
– MouseListener interface
– MouseAdapter
• Threads
– main thread listens for events and paints the
– each ball controlled by an independent thread
• Vectors -- use of a collector class
• Exceptions – used in PinBallThread
• PinBallTarget Interface – used to achieve
Handling Mouse Events
• More generally, though, we will want to trap and respond
to any mouse action, anywhere within the frame.
• Any listener that wishes to monitor mouse activity must
implement the MouseListener interface:
public interface MouseListener {
public void mouseClicked ( MouseEvent e );
public void mouseEntered ( MouseEvent e );
public void mouseExited ( MouseEvent e );
public void mousePressed ( MouseEvent e );
public void mouseReleased( MouseEvent e );
The MouseListener interface is part of the package
java.awt.event. It specifies what an object must do to be
a mouse listener within the Java Event Model.
Mouse Events in the Pin Ball
In the PinBallGame class, we have the following class relationship:
Using Vector
import java.util.Vector;
private Vector balls;
// holds only objects
balls = new Vector( ); // create a Vector
Using the Vector:
balls.addElement(newBall); // add element
balls.size( );
// return # elements
// Retrieving an element requires a cast
PinBall aBall = (PinBall) balls.elementAt (i);
Threads of Execution
What? How? Why?
The Thread class provides methods to start, run,
sleep, and stop an independent path of
computation, among other things. The start()
method manages the overhead of threads for
us; we can simply watch them go! (This is similar
to the benefits we get from using Frames...)
The pinball game separates these responsibilities
into different objects:
• painting the frame
• controlling the movement/location of balls
More on Threads
• We can think of separate threads as separate
programs running concurrently.
• They don’t literally run at the same time (unless
you have a machine with more than one CPU).
Instead, one thread gets the CPU for a while,
then it gets put on hold while another thread
gets the CPU, and so on.
• When separate threads are running, sometimes
we need to worry about two threads taking
actions that conflict with one another. We can
use the keyword synchronized to have the JVM
help maintain order.
A Problem Caused by
Separate Threads of Control
More on Threads
• Example: The second version of the pin ball game keeps
track of the score the user earns for hitting targets in the
field of play. It keeps track of the score in an instance
variable named score:
private int score = 0;
• When a pin ball strikes a target, the target tells the pin
ball game to add its point total to the instance variable by
sending an addScore message:
public void addScore( int value ) {
score = score + value;
scoreLabel.setText( "score = " + score );
A Problem Caused by
Separate Threads of Control
The solution
synchronized public void
addScore( int value ) {
score = score + value;
scoreLabel.setText( "score = "
+ score );
The keyword synchronized is used to ask
Java to guarantee that only one thread at a time
can be executing the addScore() method.
PinBall Version 2
• Adds targets for the
PinBalls to bounce
off of and score on
• Types of targets:
– Spring
– Wall
– Hole
– ScorePad
• What do all targets
have in common?
PinBallTarget Interface
interface PinBallTarget {
public boolean intersects (Ball aBall);
public void moveTo (int x, int y);
public void paint (Graphics g);
public void hitBy (Ball aBall);
Why use an interface?
– we want to process targets uniformly, e.g., check if a ball hit it
– the interface makes them the same “type” for storage in a Vector
Hole target
• structurally similar to a ball
– round like a ball
– has a location on the frame like a ball
• behavioral
– it must adhere to the interface
class Hole extends Ball implements PinBallTarget
Inherits moveTo and paint, but supplies
intersects and hitBy
Chapter 8 -- Understanding
• Inheritance
– Purpose
• Substitutability
– Relationship to inheritance
– Advantages
• Types of Inheritance
Specification (and abstract classes)
A mechanism for reusing code in an existing class.
A mechanism for organizing kinds of objects that have
the same implementation.
Create a class that extends another class.
Who wants to rewrite code??
Reuse provides:
• reliability through continual testing
• shorter development time
• ability to build frameworks (don’t call us...)
You can quickly build an application for demonstration
In one sense, a subclass is an expansion of its
• a subclass can add instance variables and methods
In another sense, a subclass is a contraction of its
• a subclass defines a subset of instances of its superclass
In Java, all classes are subclasses, whether we say so or
not. By default, any class that does not have an
extends clause extends the class Object.
Consider our Ball hierarchy: Ball, MovableBall,
Inheritance and Substitutability
An object X is substitutable for an object Y if
• we can use X any place we use Y and
• the client code not know the difference.
An example in practice, from the pinball games:
• The target vector holds any Object. That’s how Java
Vectors work.
• We put Springs, Walls, Holes, ..., into the vector.
• When we retrieve objects from the vector, we treat
them as PinBallTargets.
The common feature in these cases — and
the key to substitutability — is that the
objects share a common interface.
They respond to the same messages.
Inheritance and interfaces are mechanisms
for ensuring the common interface.
So, why write our programs so that they use
substitutable objects?
• extendibility
• flexibility
• frameworks that implement a program’s control while
allowing programmers to add new objects to the
program later
Of course, we can achieve these benefits without
the use of inheritance and interfaces. But the
compiler wouldn’t be able to help us enforce
Types of Inheritance
• Essentially no new methods in the subclass.
• Most subclass methods override inherited
• example: our BoundedBall class
• common in frameworks
Types of Inheritance
• Superclass provides responsibility but no behavior.
• Implement an interface or extend an abstract class.
• example: our event listeners
• example: pinball targets
private class MouseKeeper extends MouseAdapter {
private PinBallTarget element;
public void mousePressed ( MouseEvent e ) { ... }
public void mouseReleased( MouseEvent e ) { ... }
Types of Inheritance
• Superclass provides responsibility but no behavior.
• Implement an interface or extend an abstract class.
• example: our event listeners
• example: pinball targets
private class MouseKeeper extends MouseAdapter {
private PinBallTarget element;
public void mousePressed ( MouseEvent e ) { ... }
public void mouseReleased( MouseEvent e ) { ... }
Number - Abstract Class Example
• Parent class for numeric wrapper classes:
Integer, Long, Double, etc.
• Subclasses must override abstract methods
public abstract class Number {
public abstract int intValue();
public abstract long longValue();
public abstract float floatValue();
public abstract double doubleValue()
public byte byteValue() {return (byte) intValue;}
public short shortValue() {
return (short) intValue();
} // end Number
Types of Inheritance
• Subclass uses most or all inherited methods
• Subclass adds new behavior and methods.
• example: our MovableBall class
Types of Inheritance
• A class inherits from two or more classes. This is called multiple
• Some OOP languages provide it (C++). Some don’t (Java, Smalltalk).
• Java does support combination through interfaces.
• example: Budd’s Hole class
class Hole extends Ball implements PinBallTarget {
public Hole( int x, int y ) { ... }
public boolean intersects( Ball aBall ) { ... }
public void hitBy ( Ball aBall ) { ... }
Other Types of Inheritance
• The subclass primarily has methods that
override inherited methods.
• to restrict a behavior (example: Square
extends Rectangle)
• to remove a behavior (example: Set extends
• Limitation violates the principle of
Other Types of Inheritance
• The subclass reuses a class because it
provides needed functionality...
• ... but it is not necessarily true that an instance
of the subclass is an instance of the
• example: Java’s Stack class (ouch!)
• Construction may violate the principle of
Chapter 10 – Mechanisms for
Software Reuse
• ProjectileWorld Framework
• Java I/O: Example of Combining Inheritance and
• Decorator Pattern – DeceleratingBall example
• Novel Forms of Software Reuse
– Dynamic Composition
– Inheritance of Inner Classes
• as in listener classes
– Unnamed Classes – difficult to read, so avoid using
Chapter 11 – Implications of
• Polymorphism
• Polymorphic Variable
• Implications of Inheritance/Polymorphism
– objects reside in the heap
– reference semantics is used for assignment
and parameter passing (cloneable interface)
– equality is identity, i.e., reference comparison
– automatic garbage collection
• Memory Layout
Chapter 12 – Polymorphism
• Varieties of Polymorphism
• Pure Polymorphism
• Overloading / Ad hoc Polymorphism
– Overloading from Separate Classes
– Parametric Overloading
• Overriding
• Generic
• Efficiency and Polymorphism
• Many languages are statically-typed, that is, they require us to
declare the type of a variable in our code. Ada generics and C++
templates are constructs that provide polymorphism of this sort, in a
statically-typed way. Java 5.0 (aka Java 1.5) supports generic
classes, too!
template <class Worker>
public class Decorator {
Worker myInstanceVariable;
public Worker getValue() { return myInstanceVariable; }
• This allows me to create decorators for objects of any type:
– Decorator<int>
– Decorator<Ball>
• This mechanism enables programmers to create nearly-pure
polymorphism by declaring the kind of object that can be "wrapped".
The template gives enough information that the compiler can verify
that the polymorphic behavior will exist at run-time.