Lecture 3: Fields, Getters and Setters, Constructors, Testing
Lecture 3: Fields, Getters and Setters, Constructors, Testing
LECTURE 3: FIELDS,
GETTERS AND SETTERS,
CONSTRUCTORS, TESTING
Penkom2013
Overview
3
Homework
5
class Time
6
A class Time
7
Time@fa8
hr 9
Time
min
Class invariant
8
private, so it cant be
No way to
store value
in a field!
We can add
a setter
method
Time@fa8
hr 9
Time
getHour()
getMin()
setHour(int)toString()
setHour(int) is now in the object
min
Do not say
/** An instance maintains a time of day */
set field hr
public class Time {
to h
private int hr; //hour of day, in 0..23
private int min; // minute of hour, in 0..59
User does not
know there is a
@Test
public void testSetters() {
Time t1= new Time();
t1.setHour(21);
assertEquals(21,
t1.getHour());
}
}
public class C {
private int a;
private int b;
private int c;
private int d;
private int e;
}
C var= new
C();
var.setA(2);
var.setB(20);
var.setC(35);
var.setD(-15);
Purpose of
constructor:
Initialize field of a
new object so
that its class
Memorize!
invariant is true
Precondition: h in 0..23, m in 0..59 */ Need precondition
No return type
or void
Name of constructor
is the class name
Time@fa8
hr 9 min 5
Time
getHour() getMin()
toString() setHour(int)
Time(int, int)
Syntax of new-expression:
new <constructorcall>
Example:
new Time(9, 5)
Time@fa8
Evaluation of new-expression:
1. Create a new object of class, with default
values
in fields
2. Execute
the constructor-call
3. Give as value of the
expression
the name of the new
Ifobject
you do not declare a constructor,
Java puts in this one:
public <class-name> () { }
Time@fa8
hr 90 min 50
Time
getHour() getMin()
toString() setHour(int)
Time(int, int)
purpose: check
}
constructor
A second constructor
20
Time is
/** An object maintains a time of day */
overloaded: 2
public class Time {
constructors!
private int hr; //hour of day, 0..23
private int min; // minute of hour, 0..59 Have different
parameter types.
/** Constructor: an instance with
Constructor call
m minutes.
determines which
Precondition: m in 0..23*60 +59 */ one is called
public Time(int m) {
Time@fa8
??? What do we put here ???
hr 9 min 5 Time
}
getHour() getMin()
new Time(9, 5)
toString() setHour(int)
new Time(125)
Time(int, int) Time (int)
getHour()
getMin()
Specs of methods stay the same.
setHour(int)toString()
Implementations, including fields, change
min