Transcript ppt

Objects and Classes, take 2
Managing Complexity with Programmer-Defined Types
 Classes are programmer-defined types.
All data types other than primitive types (char,
int, double, boolean) are written/defined by
programmers, including classes from the Java
Standard Library

 Classes help us manage complexity, since they:
 tie together related data and operations
 decompose an application into some number of
objects and their interactions
can be re-used in different applications
based on slides at buildingjavaprograms.com
A programming problem
 Given a file of cities' (x, y) coordinates,
which begins with the number of cities:
6
50 20
90 60
10 72
74 98
5 136
150 91
 Write a program to draw the cities on a DrawingPanel, then
drop a "bomb" that turns all cities red that are within a
given radius:
Blast site x/y? 100 100
Blast radius? 75
2
A bad solution
Scanner input
int cityCount
int[] xCoords
int[] yCoords
=
=
=
=
new Scanner(new File("cities.txt"));
input.nextInt();
new int[cityCount];
new int[cityCount];
for (int i = 0; i < cityCount; i++) {
xCoords[i] = input.nextInt();
// read each city
yCoords[i] = input.nextInt();
}
...
 parallel arrays: 2+ arrays with related data at same indexes.

Poor solution - as the programmer, you must remember the
connection between entries in the int arrays - the program
does not tie them together.
3
Observations
 This problem would be easier to solve if
there were such a thing as a Point object.
 A Point would store a city's x,y data.
 We could compare distances between Points
to see whether the bomb hit a given city.
 Each Point would know how to draw itself.
 The overall program would be shorter and cleaner.
 A city’s coordinates would be logically connected in
the program.
4
Clients of objects
 client program: A program that uses objects.
 Example: Circles is a client of DrawingPanel and
Graphics.
Circles.java (client program)
public class Circles {
main(String[] args) {
new DrawingPanel(...)
new DrawingPanel(...)
...
}
}
DrawingPanel.java (class)
public class DrawingPanel {
...
}
5
Classes and objects
 class: A program entity that represents either:
1. A program / module, or
2. A template for a new type of objects.
 A blueprint for a collection of similar objects,
that have similar attributes and behavior
 The DrawingPanel class is a template for creating
DrawingPanel objects.
 object: An entity that combines state and behavior.
 object-oriented programming (OOP): Programs
that perform their behavior as interactions between
objects.
6
Blueprint analogy
iPod blueprint
state:
current song
volume
battery life
behavior:
power on/off
change station/song
change volume
choose random song
creates
iPod #1
iPod #2
iPod #3
state:
song = "1,000,000 Miles"
volume = 17
battery life = 2.5 hrs
state:
song = "Letting You"
volume = 9
battery life = 3.41 hrs
state:
song = "Discipline"
volume = 24
battery life = 1.8 hrs
behavior:
power on/off
change station/song
change volume
choose random song
behavior:
power on/off
change station/song
change volume
choose random song
behavior:
power on/off
change station/song
change volume
choose random song
7
Abstraction
 abstraction: A distancing between ideas and details.
 We can use objects without knowing how they work.
 abstraction in an iPod:
 You understand its external behavior (buttons,
screen).
 You don't understand its inner details, and you don't
need to, in order to use an iPod.
8
Class Design
 In the following slides, we will implement a Point class
as a way of learning about classes.
 We will define a type of objects named Point.
 Each Point object will contain x,y data called fields.
 Each Point object will contain behavior called
methods.
 Client programs will use the Point objects.
 To create a new class, think about the objects that
will be created of this new class type:
 what the object knows
 what the object does
9
Class Design
 For a Car class:
 What does a Car object know? (What attributes does
it have?)
 What can a Car object do? (What actions can it carry
out?)
 Instance variables are an object’s data, i.e., the
things the object knows about itself.
 Methods are the things an object can do.
 Note: Often our classes contain methods that
 read new values to store in instance variables,
 write the data stored in the instance variables.
10
Point objects
Point p1 = new Point(5, -2);
Point p2 = new Point();
 Data in each Point object:
// origin, (0, 0)
Field
name
x
y
Description
the point's xcoordinate
the point's ycoordinate
 Methods in each Point object:
Method name
setLocation(x, y)
Description
sets the point's x and y to the given values
translate(dx, dy) adjusts the point's x and y by the given
amounts
distance(p)
how far away the point is from point p
draw(g)
displays the point on a drawing panel
11
Point class as blueprint
Point class
state:
int x,
y
behavior:
setLocation(int x, int y)
translate(int dx, int dy)
distance(Point p)
draw(Graphics g)
Point object #1
state:
x = 5,
y = -2
behavior:
setLocation(int x, int y)
translate(int dx, int dy)
distance(Point p)
draw(Graphics g)
Point object #2
state:
x = -245,
y = 1897
behavior:
setLocation(int x, int y)
translate(int dx, int dy)
distance(Point p)
draw(Graphics g)
Point object #3
state:
x = 18,
y = 42
behavior:
setLocation(int x, int y)
translate(int dx, int dy)
distance(Point p)
draw(Graphics g)
 The class (blueprint) describes how to create objects.
 Each object contains its own data and methods.
12
Point class, version 1: State
public class Point {
private int x;
private int y;
}
 Save this code in file Point.java.
 The above code creates a new type named Point.
 Each Point object contains two pieces of data:


an int named x, and
an int named y.
 Point objects do not contain any behavior (yet).
13
Fields
 field: A variable inside an object that is part of its
state. Called an instance variable or instance field.
 Each object has its own copy of each field.
 Declaration syntax:
<access> <type> <name>;
 Example:
public class Student {
private String name;// each Student object
private double gpa;// name and gpa field
}
14
Accessing fields
 Other classes can access/modify an object's fields, if
permitted by the access specifier for the field.
 access:
 modify:
variable.field
variable.field = value;
 Example:
Point p1 = new Point();
Point p2 = new Point();
System.out.println("the x-coord is " + p1.x);// access
p2.y = 13;// modify - usually disallowed (encapsulation)
15
A class and its client
 Point.java is not, by itself, a runnable program.
 A class can be used by client programs.
PointMain.java (client program)
public class PointMain {
... main(args) {
Point p1 = new Point();
p1.x = 7;
p1.y = 2;
Point p2 = new Point();
p2.x = 4;
p2.y = 3;
...
}
}
Point.java (class of objects)
public class Point {
int x;
int y;
}
x
7
y
2
x
4
y
3
16
PointMain client example
public class PointMain {
public static void main(String[] args) {
// create two Point objects
Point p1 = new Point();
p1.y = 2;
Point p2 = new Point();
p2.x = 4;
System.out.println(p1.x + "," + p1.y);
// 0,2
// move p2 and then print it
p2.x += 2;
p2.y++;
System.out.println(p2.x + "," + p2.y);
// 6,1
}
}
17
Methods: An Object’s Behavior
 Methods of objects (methods that are non-static)
define the behavior of the object.
public class Point {
private int x;
private int y;
public void setLocation(int newX, int newY) {
x = newX;
y = newY;
}
}
18
More on Methods + this
keyword
 The keyword this allows an object to refer to itself:
public void setLocation(int x, int y) {
this.x = x;// this.x is instance var for this object
this.y = y;
}
 this is used to distinguish between the instance variable
and parameter of the same name.
 an instance method is executed from the context or
perspective of a particular object
 this lets you refer to the object on which the method is
running.
 this is called the “implicit parameter”
19
Constructors




Method that executes when a new object is created
Same name as the class
No return type - implicitly returns new object
Used to initialize object’s data fields
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
20
Accessors or Getters
 Many classes include methods that get, or return, the
value of an instance variable. This is needed if clients
need access to variable values, since we protect our
instance variables (by declaring them private)
 This methods are called accessors or getters, and
usually have the name get<VariableName>.
 Getter for x coordinate, in Point class:
public class Point {
private int x;// x cannot be modified from outside class
private int y;
public int getX() {
return x;
}
21
Mutators or Setters
 Many classes contain methods that allow a user to
modify the value of an instance variable, often with
restrictions on the type of modifications allowed.
 These methods are called mutator or setter methods.
public class Point {
private int x;
public void setX(int newX) {
x = newX;
}
}
22
Point class - Exercise
 Write a complete Point class that contains:
 a constructor that takes as arguments the





coordinates of the point
a constructor that takes no arguments, and initializes
the point to represent the origin (0, 0)
mutator methods for both the x and y coordinates
accessor methods for both the x and y coordinates
a distanceToOrigin method that computes the distance
to (0, 0) from the current point
a distance method that takes a Point p as its
argument, and returns the distance from this point to
p
23
Point Objects
 Instance method: method that exists inside each object
Point p = new Point(2, 3);
p.setLocation(4, 1);
Point q = new Point(5, 5);
q.setLocation(0, 0);
p
x
2
y
3
public void setLocation(int x, int y)
{ ... }
q
x
y
5
5
public void setLocation(int x, int y)
{ ... }
24
More on Constructors
 Initializes the state of a new object
 Runs when the client creates a new object using the
new keyword + the class/constructor name
 If a class contains no constructor, Java provides the
class with a default constructor that takes no
arguments
Syntax:
public <ClassName> (<type1> <parm1>, ... ) {
<statements that initialize instance variables>
}
25
Common Constructor Errors
 Including a return type:
public void Point(int newX, int newY) {
...
}
Remember that a constructor automatically returns the
new Point object.
 Assigning values to local variables (the constructor’s
parameter) rather than instance variables:
public void Point(int newX, int newY) {
newX = x; // assign parameter the value of
// instance variable
int y = newY; // create local variable y
}
26
Arrays of objects
 null : A reference that does not refer to any object.
 The elements of an array of objects are initialized to
null.
String[] words = new String[5];
DrawingPanel[] windows = new DrawingPanel[3];
words
window
s
index
0
1
2
3
4
value
null
null
null
null
null
index
0
1
2
value
null
null
null
27
Things you can do w/ null
 store null in a variable or an array element
String s = null;
words[2] = null;
 print a null reference
System.out.println(s);
// output: null
 ask whether a variable or array element is null
if (words[i] == null) { ...
 pass null as a parameter to a method
 return null from a method (often to indicate failure)
28
Null pointer exception
 dereference: To access data or methods of an object with the dot
notation, such as s.length().
 It is illegal to dereference null (causes an exception).
 null is not any object, so it has no methods or data.
String[] words = new String[5];
System.out.println("word is: " + words[0]);
words[0] = words[0].toUpperCase();
Output:
word is: null
Exception in thread "main"
java.lang.NullPointerException
at Example.main(Example.java:8)
29
Looking before you leap
 You can check for null before calling an object's
methods.
String[] words = new String[5];
words[0] = "hello";
words[2] = "goodbye";// words[1], [3], [4] are
null
for (int i = 0; i < words.length; i++) {
if (words[i] != null) {
words[i] = words[i].toUpperCase();
}
}
index
0
1
2
3
words
value
"hello"
null
"goodbye"
null
4
null
30
Two-phase initialization
1) initialize the array itself (each element is initially
null)
2) initialize each element of the array to be a new
object
String[] words = new String[4]; // phase 1
for (int i = 0; i < words.length; i++) {
coords[i] = "word " + i; // phase 2
}
words
index
0
1
2
3
value
"word 0"
"word 1"
"word 2"
"word 3"
31