Ch08-Classes
Ch08-Classes
Chapter 8
Classes
3
Observations
• The data in this problem is a set of points.
• It would be better stored as Point objects.
– A Point would store a city's x/y data.
4
Clients of objects
• client program: A program that uses objects.
– Example: Bomb is a client of DrawingPanel and Graphics.
DrawingPanel.java (class)
Bomb.java (client program)
public class DrawingPanel {
public class Bomb {
...
main(String[] args) {
}
new DrawingPanel(...)
new 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.
6
Blueprint analogy
iPod blueprint
state:
current song
volume
battery life
behavior:
power on/off
change station/song
change volume
choose random song
creates
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.
8
Our task
• In the following slides, we will implement a Point class as a
way of learning about defining classes.
9
Point objects (desired)
Point p1 = new Point(5, -2);
Point p2 = new Point(); // origin, (0, 0)
13
Fields
• field: A variable inside an object that is part of its state.
– Each object has its own copy of each field.
• Declaration syntax:
type name;
– Example:
public class Student {
String name; // each Student object has a
double gpa; // name and gpa field
}
14
Accessing fields
• Other classes can access/modify an object's fields.
– access: variable.field
– modify: 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
15
A class and its client
• Point.java is not, by itself, a runnable program.
– A class can be used by client programs.
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
Arrays of objects
• null : A value 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];
index 0 1 2 3 4
words value null null null null null
index 0 1 2
windows
value null null null
18
Things you can do w/ null
• store null in a variable or an array element
String s = null;
words[2] = null;
index 0 1 2 3 4
Output: value null null null null null
word is: null
Exception in thread "main"
java.lang.NullPointerException
at Example.main(Example.java:8)
20
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
index 0 1 2 3 4
words
value "HELLO" null "GOODBYE" null null
21
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
index 0 1 2 3
words
value "word0" "word1" "word2" "word3"
22
Bomb answer 1
import java.awt.*;
import java.io.*;
import java.util.*;
23
Bomb answer 2
// Reads input file of cities and returns them as array of Points.
public static Point[] readCities(Scanner input, Graphics g) {
int numCities = input.nextInt(); // first line = # of cities
Point[] cities = new Point[numCities];
for (int i = 0; i < cities.length; i++) {
cities[i] = new Point();
cities[i].x = input.nextInt(); // read city x/y from file
cities[i].y = input.nextInt();
g.fillOval(cities[i].x, cities[i].y, 3, 3);
g.drawString("(" + cities[i].x + ", " + cities[i].y + ")",
cities[i].x, cities[i].y);
}
return cities;
}
// Simulates dropping a bomb at the given location on the given cities.
public static void boom(Point bomb, int radius, Point[] cities, Graphics g) {
g.setColor(Color.RED);
g.drawOval(bomb.x - radius, bomb.y - radius, 2 * radius, 2 * radius);
for (int i = 0; i < cities.length; i++) {
int dx = cities[i].x - bomb.x;
int dy = cities[i].y - bomb.y;
double distance = Math.sqrt(dx * dx + dy * dy);
if (distance <= radius) {
g.fillOval(cities[i].x, cities[i].y, 3, 3);
g.drawString("(" + cities[i].x + ", " + cities[i].y + ")",
cities[i].x, cities[i].y);
}
}
System.out.println("Kaboom!");
}
}
24
Object behavior: Methods
Client code redundancy
• Our client program wants to draw Point objects:
// draw each city
g.fillOval(cities[i].x, cities[i].y, 3, 3);
g.drawString("(" + cities[i].x + ", " + cities[i].y + ")",
cities[i].x, cities[i].y);
26
Eliminating redundancy, v1
• We can eliminate the redundancy with a static method:
// Draws the given point on the DrawingPanel.
public static void draw(Point p, Graphics g) {
g.fillOval(p.x, p.y, 3, 3);
g.drawString("(" + p.x + ", " + p.y + ")", p.x, p.y);
}
27
Problem with static method
• We are missing a major benefit of objects: code reuse.
– Every program that draws Points would need a draw method.
Example:
public void shout() {
System.out.println("HELLO THERE!");
}
29
Instance method example
public class Point {
int x;
int y;
// Draws this Point object with the given pen.
public void draw(Graphics g) {
...
}
}
30
Point objects w/ method
• Each Point object has its own copy of the draw method, which
operates on that object's state:
p1
Point p1 = new Point();
p1.x = 7;
p1.y = 2;
x 7 y 2
Point p2 = new Point(); public void draw(Graphics g) {
p2.x = 4; // this code can see p1's x and y
p2.y = 3; }
p1.draw(g);
x 4 y 3
p2.draw(g); p2
public void draw(Graphics g) {
// this code can see p2's x and y
}
31
The implicit parameter
• implicit parameter:
The object on which an instance method is called.
32
Point class, version 2
public class Point {
int x;
int y;
// Changes the location of this Point object.
public void draw(Graphics g) {
g.fillOval(x, y, 3, 3);
g.drawString("(" + x + ", " + y + ")", x, y);
}
}
– Each Point object contains a draw method that draws that point
at its current x/y position.
33
Kinds of methods
• accessor: A method that lets clients examine object state.
– Examples: distance, distanceFromOrigin
– often has a non-void return type
34
Mutator method questions
• Write a method setLocation that changes a Point's
location to the (x, y) values passed.
35
Mutator method answers
public void setLocation(int newX, int newY) {
x = newX;
y = newY;
}
36
Accessor method questions
• Write a method distance that computes the distance
between a Point and another Point parameter.
37
Accessor method answers
public double distance(Point other) {
int dx = x - other.x;
int dy = y - other.y;
return Math.sqrt(dx * dx + dy * dy);
}
38
Printing objects
• By default, Java doesn't know how to print objects:
Point p = new Point();
p.x = 10;
p.y = 7;
System.out.println("p is " + p); // p is Point@9e8c34
// desired behavior
System.out.println("p is " + p); // p is (10, 7)
39
The toString method
tells Java how to convert an object into a String
Point@9e8c34
40
toString syntax
public String toString() {
code that returns a String representing this object;
}
– Example:
// Returns a String representing this Point.
public String toString() {
return "(" + x + ", " + y + ")";
}
41
Object initialization:
constructors
Initializing objects
• Currently it takes 3 lines to create a Point and initialize it:
Point p = new Point();
p.x = 3;
p.y = 8; // tedious
43
Constructors
• constructor: Initializes the state of new objects.
public type(parameters) {
statements;
}
...
}
45
Tracing a constructor call
• What happens when the following call is made?
Point p1 = new Point(7, 2);
p1 x y
46
Client code, version 3
public class PointMain3 {
public static void main(String[] args) {
// create two Point objects
Point p1 = new Point(5, 2);
Point p2 = new Point(4, 3);
// print each point
System.out.println("p1: (" + p1.x + ", " + p1.y + ")");
System.out.println("p2: (" + p2.x + ", " + p2.y + ")");
// move p2 and then print it again
p2.translate(2, 4);
System.out.println("p2: (" + p2.x + ", " + p2.y + ")");
}
}
OUTPUT:
p1: (5, 2)
p2: (4, 3)
p2: (6, 7)
47
Multiple constructors
• A class can have multiple constructors.
– Each one must accept a unique set of parameters.
48
Common constructor bugs
1. Re-declaring fields as local variables ("shadowing"):
public Point(int initialX, int initialY) {
int x = initialX;
int y = initialY;
}
– This declares local variables with the same name as the fields, rather
than storing values into the fields. The fields remain 0.
51
Private fields
A field that cannot be accessed from outside the class
– Examples:
private int id;
private String name;
System.out.println(p1.getX());
p1.setX(14);
53
Point class, version 4
// A Point object represents an (x, y) location.
public class Point {
private int x;
private int y;
public Point(int initialX, int initialY) {
x = initialX;
y = initialY;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
public void setLocation(int newX, int newY) {
x = newX;
y = newY;
}
public void translate(int dx, int dy) {
setLocation(x + dx, y + dy);
}
}
54
Benefits of encapsulation
• Abstraction between object and clients
56
Variable shadowing
• shadowing: 2 variables with same name in same scope.
– Normally illegal, except when one variable is a field.
• Inside setLocation,
– To refer to the data field x, say this.x
– To refer to the parameter x, say x
58
Calling another constructor
public class Point {
private int x;
private int y;
public Point() {
this(0, 0); // calls (x, y) constructor
}
...
}
• Advantages:
– code reuse
– splits up the program logic into manageable chunks
Main Class #1
main
method1
method2
Class #2 Class #3
method3 method4
method5 method6
61
Redundant program 1
// This program sees whether some interesting numbers are prime.
public class Primes1 {
public static void main(String[] args) {
int[] nums = {1234517, 859501, 53, 142};
for (int i = 0; i < nums.length; i++) {
if (isPrime(nums[i])) {
System.out.println(nums[i] + " is prime");
}
}
}
// Returns the number of factors of the given integer.
public static int countFactors(int number) {
int count = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
count++; // i is a factor of the number
}
}
return count;
}
// Returns true if the given number is prime.
public static boolean isPrime(int number) {
return countFactors(number) == 2;
}
}
62
Redundant program 2
// This program prints all prime numbers up to a maximum.
public class Primes2 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Max number? ");
int max = console.nextInt();
for (int i = 2; i <= max; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
} }
System.out.println();
}
// Returns true if the given number is prime.
public static boolean isPrime(int number) {
return countFactors(number) == 2;
}
// Returns the number of factors of the given integer.
public static int countFactors(int number) {
int count = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
count++; // i is a factor of the number
} }
return count;
}
}
63
Classes as modules
• module: A reusable piece of software, stored as a class.
– Example module classes: Math, Arrays, System
// This class is a module that contains useful methods
// related to factors and prime numbers.
public class Factors {
// Returns the number of factors of the given integer.
public static int countFactors(int number) {
int count = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
count++; // i is a factor of the number
}
}
return count;
}
// Returns true if the given number is prime.
public static boolean isPrime(int number) {
return countFactors(number) == 2;
}
}
64
More about modules
• A module is a partial program, not a complete program.
– It does not have a main. You don't run it directly.
– Modules are meant to be utilized by other client classes.
• Syntax:
class.method(parameters);
• Example:
int factorsOf24 = Factors.countFactors(24);
65
Using a module
// This program sees whether some interesting numbers are prime.
public class Primes {
public static void main(String[] args) {
int[] nums = {1234517, 859501, 53, 142};
for (int i = 0; i < nums.length; i++) {
if (Factors.isPrime(nums[i])) {
System.out.println(nums[i] + " is prime");
}
}
}
}
...
67
Static members
• static: Part of a class, rather than part of an object.
– Object classes can have static methods and fields.
– Not copied into each object; shared by all objects of that class.
class
state:
private static int staticFieldA
private static String staticFieldB
behavior:
public static void someStaticMethodC()
public static void someStaticMethodD()
– Example:
private static int theAnswer = 42;
69
Accessing static fields
• From inside the class where the field was declared:
fieldName // get the value
fieldName = value; // set the value
– generally static fields are not public unless they are final
public BankAccount() {
objectCount++; // advance the id, and
id = objectCount; // give number to account
}
...
public int getID() { // return this account's id
return id;
}
}
71
Static methods
// the same syntax you've already used for methods
public static type name(parameters) {
statements;
}
• Exercise: Make it so that clients can find out how many total
BankAccount objects have ever been created.
72
BankAccount solution
public class BankAccount {
// static count of how many accounts are created
// (only one count shared for the whole class)
private static int objectCount = 0;
// clients can call this to find out # accounts created
public static int getNumAccounts() {
return objectCount;
}
// fields (replicated for each object)
private String name;
private int id;
public BankAccount() {
objectCount++; // advance the id, and
id = objectCount; // give number to account
}
...
public int getID() { // return this account's id
return id;
}
}
73
Summary of Java classes
• A class is used for any of the following in a large program:
– a program : Has a main and perhaps other static methods.
• example: GuessingGame, Birthday, MadLibs, CritterMain
• does not usually declare any static fields (except final)