2. 2
Objects
• An object is a programming entity that contains state and
behavior.
• The state is the set of values stored in an object.
• The behavior is the set of actions an object can perform, often
reporting or modifying its internal state.
state behavior
int minute
int hour
boolean shouldAlarm
int alarmMinute
int alarmHour
setTime(...)
toggleAlarm(...)
Monday, October 7, 13
3. 3
Classes and objects
• You already know how to create classes:
public class MyProgram {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
• Classes can also create new types, similar to String or Math
Monday, October 7, 13
4. 4
Point
• Let’s create a Point object (from java.awt.Point)
Point p = new Point(3, 8);
• The Point stores its state; int values for x, y
• The Point also has behavior:
method description
translate(dx, dy) Translates the coordinates by the given amounts
setLocation(x, y) Sets the coordinates to the given values
distance(p2) Returns the distance from this point to p2
Monday, October 7, 13
5. 5
Point
import java.awt.*;
public class PointExample1 {
public static void main(String[] args) {
Point p = new Point(3, 8);
System.out.println("initially p = " + p);
p.translate(-1, -2);
System.out.println("after translating p = " + p);
int sum = p.x + p.y;
System.out.println("sum of coordinates = " + sum);
}
}
• The output:
initially p = java.awt.Point[x=3,y=8]
after translating p = java.awt.Point[x=2,y=6]
sum of coordinates = 8
Monday, October 7, 13
6. 6
Point
public class Point {
int x;
int y;
}
• Note there’s no main method; this class is not executable
public class PointMain {
public static void main(String[] args) {
Point p1 = new Point();
p1.x = 7;
p1.y = 2;
System.out.println("p1 is (" + p1.x + ", " + p1.y + ")");
}
}
Monday, October 7, 13
7. 7
Point
• Write a method that translates the coordinates of a point:
public static void translate(Point p, int dx, int dy) {
p.x = dx;
p.y = dy;
}
• static is a bad choice here; we want objects to own their
behavior
Monday, October 7, 13
8. 8
Point
public class Point {
int x;
int y;
public void translate(int dx, int dy) {
x += dx;
y += dy;
}
}
• Note we’ve dropped static! This is a method that affects an
object (remember, it gives the object behavior)
Monday, October 7, 13