Classes Chapter 4 Spring 2005 CS 101

advertisement
Classes
Chapter 4
Spring 2005
CS 101
Aaron Bloomfield
1
Preparation
 Scene so far has been background material and experience
 Computing systems and problem solving
 Variables
 Types
 Input and output
 Expressions
 Assignments
 Objects
 Standard classes and methods
 Now: Experience what Java is really about
 Design and implement objects representing information
and physical world objects
2
Object-oriented programming
 Basis
 Create and manipulate objects with attributes
behaviors that the programmer can specify
and
 Mechanism
 Classes
 Benefits
 An information type is design and implemented once
 Reused as needed
 No need reanalysis and re-justification of the
representation
3
First class – ColoredRectangle
 Purpose
 Represent a colored rectangle in a window
 Introduce the basics of object design and implementation
4
Background
 JFrame
 Principal Java class for representing a titled, bordered
graphical window.
 Standard class
 Part of the swing library
import javax.swing.* ;
5
Some Java Swing components
6
Example
 Consider
JFrame w1 = new JFrame("Bigger");
JFrame w2 = new JFrame("Smaller");
w1.setSize(200, 125);
w2.setSize(150, 100);
w1.setVisible(true);
w2.setVisible(true);
200 pixels
125
pixels
150 pixels
100
pixels
7
// Purpose: Displays two different windows.
import javax.swing.*;
public class TwoWindows {
// main(): application entry point
public static void main (String[] args) {
JFrame w1 = new JFrame("Bigger");
JFrame w2 = new JFrame("Smaller");
w1.setSize(200, 125);
w2.setSize(150, 100);
w1.setVisible(true);
w2.setVisible(true);
}
}
An optical illusion
9
Another optical illusion
10
Class ColoredRectangle – initial version
 Purpose
 Support the display of square window containing a blue
filled-in rectangle
 Window has side length of 200 pixels
 Rectangle is 40 pixels wide and 20 pixels high
 Upper left hand corner of rectangle is at (80, 90)
 Limitations are temporary
 Remember BMI.java preceded BMICalculator.java
 Lots of concepts to introduce
11
ColoredRectangle in action
 Consider
ColoredRectangle r1 = new ColoredRectangle();
ColoredRectangle r2 = new ColoredRectangle();
System.out.println("Enter when ready");
Scanner stdin = new Scanner (System.in);
stdin.nextLine();
r1.paint();
// draw the window associated with r1
r2.paint();
// draw the window associated with r2
ColoredRect angle object referenced by r1is being sent a message
r1.paint()
The messages inst ruct t he object s t o display t hemselves
r2.paint()
ColoredRect angle object referenced by r2 is being sent a message
12
// Purpose: Create two windows containing colored rectangles.
import java.util.*;
public class BoxFun {
//main(): application entry point
public static void main (String[] args) {
ColoredRectangle r1 = new ColoredRectangle();
ColoredRectangle r2 = new ColoredRectangle();
System.out.println("Enter when ready");
Scanner stdin = new Scanner (System.in);
stdin.nextLine();
r1.paint();
r2.paint();
}
}
// draw the window associated with r1
// draw the window associated with r2
ColoredRectangle.java outline
import javax.swing.*;
import java.awt.*;
public class ColoredRectangle {
// instance variables for holding object attributes
private
private
private
private
private
private
int width;
int height;
int x;
int y;
JFrame window;
Color color;
// ColoredRectangle(): default constructor
public ColoredRectangle() {
}
// ...
// paint(): display the rectangle in its window
public void paint() {
}
}
// ...
15
Instance variables and attributes
 Data field
 Java term for an object attribute
 Instance variable
 Another name for a data field
 Usually has private access
 Assists in information hiding by encapsulating the
object’s attributes
 We’ll talk more about private later
 Default initialization
 Numeric instance variables initialized to 0
 Logical instance variables initialized to false
 Object instance variables initialized to null
16
public class ColoredRectangle {
// instance variables for holding object attributes
private int width;
private int height;
private JFrame window;
private int x;
private int y;
private Color color;
// ColoredRectangle(): default constructor
public ColoredRectangle() {
window = new JFrame("Box Fun");
window.setSize(200, 200);
width = 40;
x = 80;
height = 20;
y = 90;
color = Color.BLUE;
window.setVisible(true);
}
// paint(): display the rectangle in its window
public void paint() {
Graphics g = window.getGraphics();
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
ColoredRectangle default constructor
public class
ColoredRectangle
{
// instance variables to describe object attributes
...
// ColoredRectangle(): default constructor
public ColoredRectangle() {
...
}
...
}
The name of a constructor always matches the
name of its class
A constructor does not list its return type. A constructor
always returns a reference to a new object of its class
18
Quick survey

a)
b)
c)
d)
I understand the purpose of a constructor
Very well
With some review, I’ll be good
Not really
Not at all
19
public class ColoredRectangle {
// instance variables for holding object attributes
private int width;
private int height;
private JFrame window;
private int x;
private int y;
private Color color;
// ColoredRectangle(): default constructor
public ColoredRectangle() {
window = new JFrame("Box Fun");
window.setSize(200, 200);
width = 40;
x = 80;
height = 20;
y = 90;
color = Color.BLUE;
window.setVisible(true);
}
// paint(): display the rectangle in its window
public void paint() {
Graphics g = window.getGraphics();
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
Color constants













Color.BLACK
Color.BLUE
Color.CYAN
Color.DARK_GRAY
Color.GRAY
Color.GREEN
Color.LIGHT_GRAY
Color.MAGENTA
Color.ORANGE
Color.PINK
Color.RED
Color.WHITE
Color.YELLOW
21
ColoredRectangle r = new ColoredRectangle();
r
ColorRectangle
The value of a
ColoredRectangle
variable is a
reference to a
ColoredRectangle
object
- width = 40
- height = 20
- x = 80
- y = 90
- window =
- color =
+ paint() :
String
- text
- ...
void
= "Box Fun"
+ length()
+ ...
Color
- color =
- ...
+ brighter() : Color
+ ...
: int
JFrame
- width = 200
- height = 200
- title =
- ...
+ setVisible(
+ ...
boolean
status)
: void
Quick survey

a)
b)
c)
d)
I understood the memory diagram from the
previous slide
Very well
With some review, I’ll be good
Not really
Not at all
23
Computer bugs
24
Another possible Constructor
public class ColoredRectangle {
// instance variables for holding object attributes
private int width = 40;
private int height = 80;
private JFrame window;
private int x = 80;
private int y = 90;
private Color color = Color.BLUE;
// ColoredRectangle(): default constructor
public ColoredRectangle() {
window = new JFrame("Box Fun");
window.setSize(200, 200);
window.setVisible(true);
}
25
public class ColoredRectangle {
// instance variables for holding object attributes
private int width;
private int height;
private JFrame window;
private int x;
private int y;
private Color color;
// ColoredRectangle(): default constructor
public ColoredRectangle() {
window = new JFrame("Box Fun");
window.setSize(200, 200);
width = 40;
x = 80;
height = 20;
y = 90;
color = Color.BLUE;
window.setVisible(true);
}
// paint(): display the rectangle in its window
public void paint() {
Graphics g = window.getGraphics();
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
Graphical context
 Graphics
 Defined in java.awt.Graphics
 Represents the information for a rendering request
 Color
 Component
 Font
 …
 Provides methods
 Text drawing
 Line drawing
 Shape drawing
 Rectangles
 Ovals
 Polygons
27
Java coordinate system
X-Axis
Coordinat e (0.0)
Y-Axis
Coordinat e (80, 90)
Coordinat e (120, 110)
28
Method invocation
 Consider
r1.paint();
// display window associated with r1
r2.paint();
// display window associated with r2
 Observe
 When an instance method is being executed, the
attributes of the object associated with the invocation are
accessed and manipulated
 Important that you understand what object is being
manipulated
29
Method invocation
public class
ColoredRectangle
{
// instance variables to describe object attributes
...
// paint(): display the rectangle in its window
public void paint() {
window.setVisible( true );
Graphics g = window.getGraphics();
g.setColor(color);
g.fillRect(x, y, width, height);
}
...
}
The values of these instance
variables are also from the
ColoredRectangle object
Instance variable window references
the JFrame attribute of the object
that caused the invocation.
Typo in book: p.
149 claims paint()
is static; it is not
30
Quick survey

a)
b)
c)
d)
I understood the ColoredRectangle class
Very well
With some review, I’ll be good
Not really
Not at all
31
Improving ColoredRectangle
 Analysis
 A ColoredRectangle object should
 Be able to have any color
 Be positionable anywhere within its window
 Have no restrictions on its width and height
 Accessible attributes
 Updateable attributes
32
Improving ColoredRectangle
 Additional constructions and behaviors
 Specific construction
 Construct a rectangle representation using supplied
values for its attributes
 Accessors
 Supply the values of the attributes
 Individual methods for providing the width, height, xcoordinate position, y-coordinate position, color, or
window of the associated rectangle
 Mutators
 Manage requests for changing attributes
 Ensure objects always have sensible values
 Individual methods for setting the width, height, xcoordinate position, y-coordinate position, color, or
33
window of the associated rectangle to a given value
A mutator method
 Definition
// setWidth(): width mutator
public void setWidth(int w) {
width = w;
}
 Usage
ColoredRectangle s = new ColoredRectangle();
s.setWidth(80);
Initial value of the formal parameter
comes from the actual parameter
Object to be manipulated
is the one referenced by s
public void setWidth ( int
...
}
w) {
Changes to the formal parameter
34
do not affect the actual parameter
Mutator setWidth() evaluation
ColoredRectangle s = new ColoredRectangle();
s .setWidth(80);
The invocation sends a message to the ColoredRectangle
referenced by s to modify its width attribute.
public class ColoredRectangle {
...
/ / setWidth(): width mutator
public void
setWidth ( int
w) {
width = w;
}
...
For this invocation of method
setWidth(), w is initialized to 80
Method setWidth() sets the instance variable width of its
ColoredRectangle.
}
Method setWidth() is completed. Control is transferred back
35
Today’s demotivators
36
Java parameter passing
 The value is copied to the method
 Any changes to the parameter are forgotten when the
method returns
37
Java parameter passing
 Consider the following code:
static void foobar (int y) {
y = 7;
}
y
5
7
x
5
formal parameter
public static void main (String[] args) {
int x = 5;
actual parameter
foobar (x);
System.out.println(x);
}
 What gets printed?
38
Java parameter passing
 Consider the following code:
static void foobar (String y) {
y = “7”;
}
y
“7"
x
“5"
formal parameter
public static void main (String[] args) {
String x = “5”;
actual parameter
foobar (x);
System.out.println(x);
}
 What gets printed?
39
Java parameter passing
 Consider the following code:
static void foobar (ColoredRectangle y) {
y.setWidth (10);
formal parameter
}
public static void main (String[] args) {
ColoredRectangle x = new ColoredRectangle();
foobar (x);
actual parameter
System.out.println(x.getWidth());
}
y
 What gets printed?
x
width
width==10
0
40
Java parameter passing
 Consider the following code:
static void foobar (ColoredRectangle y) {
y = new ColoredRectangle();
y.setWidth (10); formal parameter
}
public static void main (String[] args) {
ColoredRectangle x = new ColoredRectangle();
actual parameter
foobar (x);
System.out.println(y.getWidth());
}
 What gets printed?
y
width
width==10
0
x
width = 0
41
Java parameter passing
 The value of the actual parameter gets copied to the formal
parameter
 This is called pass-by-value
 C/C++ is also pass-by-value
 Other languages have other parameter passing types
 Any changes to the formal parameter are forgotten when the
method returns
 However, if the parameter is a reference to an object, that
object can be modified
 Similar to how the object a final reference points to can be
modified
42
Quick survey

a)
b)
c)
d)
I felt I understand Java parameter passing
Very well
With some review, I’ll be good
Not really
Not at all
43
Damage Control
45
The main() method

Consider a class with many methods:
public class WhereToStart {
public static void foo (int x) {
// ...
}
public static void bar () {
// ...
}
public static void main (String[] args) {
// ...
}
}

Where does Java start executing the program?
 Always at the beginning of the main() method!
46
Variable scoping

A variable is visible within the block it is declared in
 Called the “scope” of the variable
public class Scoping {
int z
This instance variable is visible
anywhere in the Scoping class
public static void foo (int x) {
// ...
}
This parameter is visible
only in the foo() method
public static void bar () {
// ...
}
public static void main (String[] args) {
int y;
This local variable is visible until
// ...
the end of the main() method
}
}
47
More on classes vs. objects
48
A new example: creating a Car class
 What properties does a car have in the real world?
 Color
 Position (x,y)
 Fuel in tank
 We will implement these properties in our Car class
public class Car {
private Color color;
private int xpos;
private int ypos;
private int fuel;
//...
}
49
Car’s instance variables
public class Car {
private Color color;
private int xpos;
private int ypos;
private int fuel;
//...
Car
}
- color
- fuel
- xpos
- ypos
+…
50
Instance variables and attributes
 Default initialization
 If the variable is within a method, Java does NOT initialize
it
 If the variable is within a class, Java initializes it as
follows:
Car
 Numeric instance
variables initialized to 0
- color = null
- xpos = 0
- fuel = 0
- ypos = 0
 Logical instance
variables initialized to
+…
false
 Object instance
variables initialized to
null
51
Car behaviors or methods
 What can a car do? And what can you do to a car?
 Move it
 Change it’s x and y positions
 Change it’s color
 Fill it up with fuel
 For our computer simulation, what else do we want the Car
class to do?
 Create a new Car
 Plot itself on the screen
 Each of these behaviors will be written as a method
52
Creating a new car
 To create a new Car, we call:
 Car car = new Car();
 Notice this looks like a method
 You are calling a special method called a constructor
 A constructor is used to create (or construct) an object
 It sets the instance variables to initial values
 The constructor:
public Car() {
fuel = 1000;
color = Color.BLUE;
}
53
Constructors
No return type!
For now, all
constructors
are public
EXACT same
name as class
public Car() {
fuel = 1000;
color = Color.BLUE;
}
54
Our Car class so far
public class Car {
private Color color;
private int xpos;
private int ypos;
private int fuel;
public class Car {
private Color color =
Color.BLUE;
private int xpos;
private int ypos;
private int fuel = 1000;
public Car() {
fuel = 1000;
color = Color.BLUE;
}
}
public Car() {
}
}
55
Our Car class so far
public class Car {
private Color color =
Color.BLUE;
private int xpos = 0;
private int ypos = 0;
private int fuel = 1000;
Car
- color = Color.BLUE
- fuel = 1000
- xpos = 0
- ypos = 0
+ Car()
+…
public Car() {
}
}
 Called the default constructor
 The default constructor has no parameters
 If you don’t include one, Java will SOMETIMES put one
56
there automatically
Another constructor
 Another constructor:
public Car (Color c, int x, int y, int f) {
color = c;
xpos = x;
ypos = y;
fuel = f;
}
 This constructor takes in four parameters
 The instance variables in the object are set to those
parameters
 This is called a specific constructor
 An constructor you provide that takes in parameters is
called a specific constructor
57
Our Car class so far
Car
public class Car {
private Color color =
Color.BLUE;
private int xpos = 0;
private int ypos = 0;
private int fuel = 1000;
- color = Color.BLUE
- fuel = 1000
- xpos = 0
- ypos = 0
+ Car()
+ Car (Color, int, int, int)
+…
public Car() {
}
public Car (Color c, int x, int y, int f) {
color = c;
xpos = x;
ypos = y;
fuel = f;
}
}
58
Using our Car class
 Now we can use both our constructors:
Car c1 = new Car();
Car c2 = new Car (Color.BLACK, 1, 2, 500);
c1
c2
Car
- color = Color.BLUE
- fuel = 1000
Car
- xpos = 0
- ypos = 0
+ Car()
+ Car (Color, int, int, int)
+…
- color = Color.BLACK - xpos = 1
- fuel = 500
- ypos = 2
+ Car()
+ Car (Color, int, int, int)
+…
59
Quick survey

a)
b)
c)
d)
How much of a Star Wars fan are you?
I already have my Episode 3 tickets
I’ll see it in the theater
I’ll rent it on DVD
Is that like that Star Trek thing?
60
Star Wars Episode 3 Trailer
61
Star Wars Episode 3 Trailer

That was a edited version
– I changed the PG-rated trailer to a G-rated
trailer

The original one can be found at
http://www.sequentialpictures.com/
– Or Google for “star wars parody”
62
So what does private mean?
 Consider the following code
Note that it’s a
different class!
public class CarSimulation {
public static void main (String[] args) {
Car c = new Car();
System.out.println (c.fuel);
}
}
 Recall that fuel is a private instance variable in the Car class
 Private means that code outside the class CANNOT access the
variable
 For either reading or writing
 Java will not compile the above code
63
 If fuel were public, the above code would work
So how do we get the fuel of a Car?
 Via accessor methods in the Car class:
public int getFuel() {
return fuel;
}
public Color getColor() {
return color;
}
public int getYPos() {
return ypos;
}
public int getXPos() {
return xpos;
}
 As these methods are within the Car class, they can read the
private instance variables
 As the methods are public, anybody can call them
64
So how do we set the fuel of a Car?
 Via mutator methods in the Car class:
public void setFuel (int f) {
fuel = f;
}
public void setColor (Color c) {
color = c;
}
public void setXPos (int x) {
xpos = x;
}
public void setYPos (int y) {
ypos = y;
}
 As these methods are within the Car class, they can read the
private instance variables
 As the methods are public, anybody can call them
65
Quick survey

a)
b)
c)
d)
I vaguely understand the public/private stuff
Very well
With some review, I’ll be good
Not really
Not at all
66
Why use all this?
 These methods are called a
get/set pair
 Used with private variables
 We’ll see why one uses these
later on in the course
 Our Car so far:
Car
- color = Color.BLUE
- fuel = 1000
- xpos = 0
- ypos = 0
+ Car()
+ Car (Color, int, int, int)
+ void setXPos (int x)
+ void setYPos (int y)
+ void setPos (int x, int y)
+ void setColor (Color c)
+ void setFuel (int f)
+ int getFuel()
+ int getXPos()
+ int getYPos()
+ Color getColor()
+…
67
Back to our specific constructor
public class Car {
private Color color =
Color.BLUE;
private int xpos = 0;
private int ypos = 0;
private int fuel = 1000;
public class Car {
private Color color =
Color.BLUE;
private int xpos = 0;
private int ypos = 0;
private int fuel = 1000;
public Car (Color c,
int x, int y, int f) {
color = c;
xpos = x;
ypos = y;
fuel = f;
}
}
public Car (Color c,
int x, int y, int f) {
setColor (c);
setXPos (x);
setYPos (y);
setFuel (f);
}
}
68
Back to our specific constructor
 Using the mutator methods (i.e. the ‘set’ methods) is the
preferred way to modify instance variables in a constructor
 We’ll see why later
69
So what’s left to add to our Car class?
 What else we should add:
 A mutator that sets both the x and y positions at the
same time
 A means to “use” the Car’s fuel
 A method to paint itself on the screen
 Let’s do the first:
public void setPos (int x, int y) {
setXPos (x);
setYPos (y);
}
 Notice that it calls the mutator methods
70
Using the Car’s fuel
 Whenever the Car moves, it should burn some of the fuel
 For each pixel it moves, it uses one unit of fuel
 We could make this more realistic, but this is simpler
public void setXPos (int x) {
xpos = x;
}
public void setXPos (int x) {
fuel -= Math.abs
(getXPos()-x);
xpos = x;
}
public void setYPos (int y) {
ypos = y;
}
public void setYPos (int y) {
fuel -= Math.abs
(getYPos()-y);
ypos = y;
71
}
Using the Car’s fuel
public void setPos (int x,
int y) {
setXPos(x);
setYPos(y);
}
public void setPos (int x,
int y) {
setXPos(x);
setYPos(y);
}
 Notice that to access the instance variables, the accessor
methods are used
 Math.abs() gets the absolute value of the passed parameter
72
Just in time for Valentine’s Day
Black Monday
73
Bittersweets: Dejected sayings
I MISS MY EX
 PEAKED AT 17
 MAIL ORDER
 TABLE FOR 1
 I CRY ON Q
 U C MY BLOG?
 REJECT PILE
 PILLOW HUGGIN

ASYLUM BOUND
 DIGNITY FREE
 PROG FAN
 STATIC CLING
 WE HAD PLANS
 XANADU 2NITE
 SETTLE 4LESS
 NOT AGAIN

74
Bittersweets: Dysfunctional sayings
RUMORS TRUE
 PRENUP OKAY?
 HE CAN LISTEN
 GAME ON TV
 CALL A 900#
 P.S. I LUV ME
 DO MY DISHES
 UWATCH CMT

PAROLE IS UP!
 BE MY YOKO
 U+ME=GRIEF
 I WANT HALF
 RETURN 2 PIT
 NOT MY MOMMY
 BE MY PRISON
 C THAT DOOR?

75
Drawing the Car
 The simple way to have the Car
draw itself:
public void paint (Graphics g) {
g.setColor (color);
g.fillRect (xpos-50, ypos-100,
100, 200);
}
 This draws a single rectangle that is 100 by 200 pixels in size
 Lets use constants for the car’s height and width...
76
Drawing the Car

A better version:
private final int CAR_WIDTH = 100;
private final int CAR_HEIGHT = 200;
public void paint (Graphics g) {
g.setColor (color);
g.fillRect (getXPos()-CAR_WIDTH/2,
getYPos()-CAR_HEIGHT/2,
CAR_WIDTH, CAR_HEIGHT);
}

This makes it easier to change the car size
 We could have made the car size instance variables and set
them via mutators

Lets add tires!
77
Drawing the Car
private
private
private
private
private
final
final
final
final
final
int
int
int
int
int
CAR_WIDTH = 100;
CAR_HEIGHT = 200;
TIRE_WIDTH = 20;
TIRE_HEIGHT = 40;
TIRE_OFFSET = 20;
public void paint (Graphics g) {
g.setColor (color);
g.fillRect (getXPos()-CAR_WIDTH/2,
getYPos()-CAR_HEIGHT/2,
CAR_WIDTH, CAR_HEIGHT);
// Draw the tires
g.setColor (Color.BLACK);
g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH),
getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT);
g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH),
getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT), Don’t worry about
TIRE_WIDTH, TIRE_HEIGHT);
this – just know that
g.fillRect (getXPos()+(CAR_WIDTH/2),
it draws four tires
getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT),
TIRE_WIDTH, TIRE_HEIGHT);
g.fillRect (getXPos()+(CAR_WIDTH/2),
getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT);
}
79
What happens when the car runs out of
fuel?

We



could do a number of things:
Not allow the car to move anymore
Print out a message saying, “fill me up!”
We’ll color the car red

We’ll insert the following code at the beginning of the paint()
method:
if ( fuel < 0 ) {
color = Color.RED;
}

We haven’t seen if statements yet
 Basically, this says that if the fuel is less than zero, color the car
red
 We’ll see if statements in chapter 5
80
Drawing the Car
private
private
private
private
private
final
final
final
final
final
int
int
int
int
int
CAR_WIDTH = 100;
CAR_HEIGHT = 200;
TIRE_WIDTH = 20;
TIRE_HEIGHT = 40;
TIRE_OFFSET = 20;
public void paint (Graphics g) {
if ( fuel < 0 ) {
color = Color.RED;
}
g.setColor (color);
g.fillRect (getXPos()-CAR_WIDTH/2,
getYPos()-CAR_HEIGHT/2,
CAR_WIDTH, CAR_HEIGHT);
// Draw the tires
g.setColor (Color.BLACK);
g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH),
getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT);
g.fillRect (getXPos()-(CAR_WIDTH/2+TIRE_WIDTH),
getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT),
TIRE_WIDTH, TIRE_HEIGHT);
g.fillRect (getXPos()+(CAR_WIDTH/2),
getYPos()+(CAR_HEIGHT/2-TIRE_OFFSET-TIRE_HEIGHT),
TIRE_WIDTH, TIRE_HEIGHT);
g.fillRect (getXPos()+(CAR_WIDTH/2),
getYPos()-(CAR_HEIGHT/2-TIRE_OFFSET), TIRE_WIDTH, TIRE_HEIGHT);
}
81
Our car in action
 ...
82
Quick survey

a)
b)
c)
d)
I understood about creating the Car class
Very well
With some review, I’ll be good
Not really
Not at all
83
The 2004 Ig Nobel Prizes







Medicine
Physics
Public Health
Chemistry
Engineering
Literature
Psychology

Economics
Peace

Biology

"The Effect of Country Music on Suicide.“
For explaining the dynamics of hula-hooping
Investigating the scientific validity of the FiveSecond Rule
The Coca-Cola Company of Great Britain
For the patent of the combover
The American Nudist Research Library
It’s easy to overlook things – even a man in a
gorilla suit.
The Vatican, for outsourcing prayers to India
The invention of karaoke, thereby providing an
entirely new way for people to learn to tolerate
each other
For showing that herrings apparently communicate
84
by farting
What I’m not expecting you to know yet…
 What the static keyword means
 And why the main() method is
 And why other methods are not
 Why you should always call the mutator methods, instead of
setting the field directly
 Just know that it’s a good programming practice, and
follow it
 We’ll see why next chapter
 Why instance variables are supposed to be private
 Just know that it’s a good programming practice, and
85
follow it
What we’ve seen so far
 Two examples of creating a class
 ColoredRectangle
 Car
 Up next: another example
 Rational
 Represents rational numbers
 A rational number is any number that can
expressed as a fraction
 Both the numerator and denominator must
integers!
 Discussed in section 4.8 of the textbook
86
be
be
What properties should our Rational class
have?
 The numerator (top part of the fraction)
 The denominator (bottom part of the fraction)
 Not much else…
87
What do we want our Rational class to
do?
 Obviously, the ability to create new Rational objects
 Setting the numerator and denominator
 Getting the values of the numerator and denominator
 Perform basic operations with rational numbers: + - * /
 Ability to print to the screen
88
Our first take at our Rational class
 Our first take
public class Rational {
private int numerator;
private int denominator;
//...
}
Rational
- numerator = 0 - denominator = 0
+…
 This does not represent a valid Rational number!
 Why not?
 Java initializes instance variables to zero
 Both the numerator and denominator are thus set to zero
 0/0 is not a valid number!
89
Our next take at our Rational class
 Our next take
public class Rational {
private int numerator = 0;
private int denominator = 1;
//...
}
 We’ve defined the attributes
of our class
Rational
- numerator = 0 - denominator = 1
+…
 Next up: the behaviors
90
The default constructor
 Ready?
Rational
- numerator = 0 - denominator = 1
public Rational() {
}
+ Rational()
+…
 Yawn!
 Note that we could have initialized the instance variables here
instead
 The default constructor is called that because, if you don’t
specify ANY constructors, then Java includes one by default
91
 Default constructors do not take parameters
The specific constructor
 Called the specific constructor because it is one that the user
specifies
 They take one or more parameters
public Rational (int num, int denom) {
setNumerator (num);
Rational
setDenominator (denom);
- numerator = 0 - denominator = 1
}
 Note that the specific constructor
calls the mutator methods instead
of setting the instance variables
directly
 We’ll see why next chapter
+ Rational()
+ Rational (int num, int denom)
+…
92
Accessor methods
 Our two accessor methods:
public int getNumerator () {
return numerator;
}
public int getDenominator () {
return denominator;
}
Rational
- numerator = 0 - denominator = 1
+ Rational()
+ Rational (int num, int denom)
+ int getNumerator()
+ int getDemonimator()
+…
93
Mutator methods
 Our two mutator methods:
public void setNumerator (int towhat) {
numerator = towhat;
}
public void setDenominator (int towhat) {
denominator = towhat;
}
94
Rational addition
 How to do Rational addition:
a c ad  bc
 
b d
bd
 Our add() method:
public Rational add (Rational other) {
}
95
The this keyword
Rational
Returns:
- numerator = 5 - denominator = 6
+ Rational ()
+ Rational (int n, int d)
+ Rational add (Rational other)
+…
this
Rational
Rational
- numerator = 1 - denominator = 2
- numerator = 1 - denominator = 3
+ Rational ()
+ Rational (int n, int d)
+ Rational
Rational add
add(Rational
(other other) )
+…
+ Rational ()
+ Rational (int n, int d)
+ Rational add (Rational other)
+…
96
The this keyword
 this is a reference to whatever object we are currently in
 Will not work in static methods
 We’ll see why later
 Note that the main() method is a static method
 While we’re at it, when defining a class, note that NONE of
the methods were static
97
Today’s demotivators
98
Rational addition
 How to do Rational addition:
a c ad  bc
 
b d
bd
 Our add() method:
public Rational add (Rational other) {
int a = this.getNumerator();
int b = this.getDenominator();
int c = other.getNumerator();
int d = other.getDenominator();
return new Rational (a*d+b*c, b*d);
}
99
Rational subtraction
 How to do Rational subtraction:
a c ad  bc
 
b d
bd
 Our subtract() method:
public Rational subtract (Rational other) {
int a = this.getNumerator();
int b = this.getDenominator();
int c = other.getNumerator();
int d = other.getDenominator();
return new Rational (a*d-b*c, b*d);
}
100
Rational multiplication
 How to do Rational multiplication:
a c ac
* 
b d bd
 Our multiply() method:
public Rational multiply (Rational other) {
int a = this.getNumerator();
int b = this.getDenominator();
int c = other.getNumerator();
int d = other.getDenominator();
return new Rational (a*c, b*d);
}
101
Rational division
 How to do Rational division:
a c ad
 
b d bc
 Our divide() method:
public Rational divide (Rational other) {
int a = this.getNumerator();
int b = this.getDenominator();
int c = other.getNumerator();
int d = other.getDenominator();
return new Rational (a*d, b*c);
}
102
Printing it to the screen
 If we try printing a Rational object to the screen:
Rational r = new Rational (1,2);
System.out.println (r);
 We get the following:
Rational@82ba41
 Ideally, we’d like something more informative printed to the
screen
 The question is: how does Java know how to print a custom
103
class to the screen?
The toString() method
 When an object is put into a print statement:
Rational r = new Rational (1,2);
System.out.println (r);
 Java will try to call the toString() method to covert the object
to a String
 If the toString() method is not found, a default one is
included
 Hence the Rational@82ba41 from the previous slide
 So let’s include our own toString() method
104
The toString() method
 Our toString() method is defined as follows:
public String toString () {
return getNumerator() + "/" + getDenominator();
}
 Note that the prototype must ALWAYS be defined as shown
 The prototype is the ‘public String toString()’
105
Printing it to the screen
 Now, when we try printing a Rational object to the screen:
Rational r = new Rational (1,2);
System.out.println (r);
 We get the following:
1/2
 Which is what we wanted!
 Note that the following two lines are equivalent:
System.out.println (r);
System.out.println (r.toString());
106
Our full Rational class
Rational
- numerator = 0 - denominator = 1
+ Rational()
+ Rational (int num, int denom)
+ int getNumerator()
+ int getDemonimator()
+ void setNumerator (int num)
+ void setDenominator (int denom)
+ Rational add (Rational other)
+ Rational subtract (Rational other)
+ Rational multiply (Rational other)
+ Rational divide (Rational other)
+ String toString()
107
Our Rational class in use, part 1 of 4


This code is in a main() method of a RationalDemo class
First, we extract the values for our first Rational object:
Scanner stdin = new Scanner(System.in);
System.out.println();
// extract values for rationals r and s
Rational r = new Rational();
System.out.print("Enter numerator of a rational number: ");
int a = stdin.nextInt();
System.out.print("Enter denominator of a rational number: ");
int b = stdin.nextInt();
r.setNumerator(a);
r.setDenominator(b);
108
Our Rational class in use, part 2 of 4
 Next, we extract the values for our second Rational object:
Rational s = new Rational();
System.out.print("Enter numerator of a rational number: ");
int c = stdin.nextInt();
System.out.print("Enter denominator of a rational number: “);
int d = stdin.nextInt();
s.setNumerator(c);
s.setDenominator(d);
 Notice that I didn’t create another Scanner object!
 Doing so would be bad
 I used the same one
109
Our Rational class in use, part 3 of 4
 Next, we do the arithmetic:
// operate on r and s
Rational sum = r.add(s);
Rational difference = r.subtract(s);
Rational product = r.multiply(s);
Rational quotient = r.divide(s);
110
Our Rational class in use, part 4 of 4
 Lastly, we print the results
// display operation results
System.out.println("For r = " + r.toString() + " and s = "
+ s.toString());
System.out.println("
r + s = " + sum.toString());
System.out.println("
r - s = " + difference.toString());
System.out.println("
r * s = " + product.toString());
System.out.println("
r / s = " + quotient.toString());
System.out.println();
111
A demo of our Rational class
 …
112
Other things we might want to add to our
Rational class
 The ability to reduce the fraction
 So that 2/4 becomes 1/2
 Not as easy as it sounds!
 More complicated arithmetic
 Such as exponents, etc.
 Invert
 Switches the numerator and denominator
 Negate
 Changes the rational number into its (additive) negation
 We won’t see any of that here
113
Quick survey

a)
b)
c)
d)
I felt I understood the Rational class…
Very well
With some review, I’ll be good
Not really
Not at all
114
Quick survey

a)
b)
c)
d)
I feel I could define my own class…
Very well
With some review, I’ll be good
Not really
Not at all
115
Quick survey

a)
b)
c)
d)
I would like to see another example of creating a
class (we probably will still do it, though)…
Definitely!
Sure, why not?
Not really
No more! I can’t take it anymore!!!!
116
Warn your grandparents!

Historically, this class has been lethal to grandparents of
students in the class
– More often grandmothers

This happens most around test time
– Although occasionally around the times a big
assignment is due
– The lower your course average, the more
likely it is to occur

http://biology.ecsu.ctstateu.edu/People/ConnRev.html
117
Java parameter passing
 The value is copied from the actual parameter to the formal
parameter
 Any changes to the formal parameter are forgotten when the
method returns
118
Java parameter passing
 Consider the following code:
static void foobar (int y) {
y = 7;
}
y
5
7
x
5
formal parameter
public static void main (String[] args) {
int x = 5;
actual parameter
foobar (x);
System.out.println(x);
}
 What gets printed?
 5
119
Java parameter passing
 Consider the following code:
y
5.0
7.0
5.0
x
static void foobar (double y) {
y = 7.0;
}
formal parameter
public static void main (String[] args) {
double x = 5.0;
actual parameter
foobar (x);
System.out.println(x);
}
 What gets printed?
 5.0
120
Java parameter passing
 Consider the following code:
static void foobar (String y) {
y = “7”;
}
y
“7"
x
“5"
formal parameter
public static void main (String[] args) {
String x = “5”;
actual parameter
foobar (x);
System.out.println(x);
}
 What gets printed?
 5
121
Java parameter passing
 Consider the following code:
static void foobar (ColoredRectangle y) {
y.setWidth (10);
}
formal parameter
public static void main (String[] args) {
ColoredRectangle x = new ColoredRectangle();
foobar (x);
actual parameter
System.out.println(x.getWidth());
}
 What gets printed?
 10
y
x
width
width==10
0
122
Java parameter passing
 Consider the following code:
static void foobar (ColoredRectangle y) {
y = new ColoredRectangle();
y.setWidth (10); formal parameter
}
public static void main (String[] args) {
ColoredRectangle x = new ColoredRectangle();
actual parameter
foobar (x);
System.out.println(y.getWidth());
}
 What gets printed?
 0
y
width
width==10
0
x
width = 0
124
Java parameter passing
 The value of the actual parameter gets copied to the formal
parameter
 This is called pass-by-value
 C/C++ is also pass-by-value
 Other languages have other parameter passing types
 Any changes to the formal parameter are forgotten when the
method returns
 However, if the parameter is a reference to an object, that
object can be modified
 Similar to how the object a final reference points to can be
modified
125
Quick survey

a)
b)
c)
d)
I felt I understand Java parameter passing
Very well
With some review, I’ll be good
Not really
Not at all
126
Casting
 We’ve seen casting before:
 double d = (double) 3;
 int x = (int) d;
 Aside: duplicating an object
 String s = “foo”;
 String t = s.clone();
 Causes an error: “inconvertible types”
 (Causes another error, but we will ignore that one)
 What caused this?
127
Casting, take 2
 .clone() returns an object of class Object (sic)
 More confusion: You can also have an object of class Class
 Thus, you can have an Object class and a Class object
 Got it?
 We know it’s a String (as it cloned a String)
 Thus, we need to tell Java it’s a String via casting
 Revised code:
 String s = “foo”;
 String t = (String) s.clone();
 Still causes that “other” error, but we are still willfully
128
ignoring it…
Casting, take 3
 That “other” error is because String does not have a .clone()
method
 Not all classes do!
 We just haven’t seen any classes that do have .clone() yet
 Check in the documentation if the object you want to copy
has a .clone() method
 A class that does: java.util.Vector
 Vector s = new Vector();
 Vector t = s.clone();
 Vector u = (Vector) s.clone();
Causes the “inconvertible
types” error
129
Casting, take 4
 What happens with the following code?
 Vector v = new Vector();
 String s = (String) v;
 Java will encounter a compile-time error
 “inconvertible types”
 What happens with the following code?
 Vector v = new Vector();
 String s = (String) v.clone();
 Java will encounter a RUN-time error
 ClassCastException
130
Quick survey

a)
b)
c)
d)
I felt I understood the material in this slide set…
Very well
With some review, I’ll be good
Not really
Not at all
131
Quick survey

a)
b)
c)
d)
The pace of the lecture for this slide set was…
Fast
About right
A little slow
Too slow
132
Quick survey

a)
b)
c)
d)
How interesting was the material in this slide
set? Be honest!
Wow! That was SOOOOOOO cool!
Somewhat interesting
Rather boring
Zzzzzzzzzzz
133
Today’s demotivators
134
Download