L07 - Classes & Objects
L07 - Classes & Objects
Examples
object state behavior
dog isHungry eat, bark
grade book grades mean, median
light on/off switch
Objects in Java
A class defines a new type of Object
class LightSwitch {
}
Fields
An Object's state is stored in variables
called fields
Fields are declared (and optionally
initialized) inside the braces of the class
Light switch example with a field . . .
class LightSwitch {
boolean on = true;
}
Methods
}
Constructing Person Objects
Person(String n, int a) {
name = n;
age = a;
}
// . . .
}
boolean on;
LightSwitch() {
on = true;
}
LightSwitch(boolean o) {
on = o;
}
}
This Keyword
Instance can refer to itself with the
keyword this
class LightSwitch {
boolean on;
LightSwitch() {
this.on = true; //(same as
on=true;)
}
LightSwitch(boolean on) {
this.on = on;
}
Cascading Constructors
A constructor can call another constructor with
this(arguments)
class LightSwitch {
boolean on;
LightSwitch() {
this(true);
}
LightSwitch(boolean on) {
this.on = on;
}
}
Classes Recap
Classes have fields to store the state of the objects
in the class and methods to provide the operations
the objects can perform.
We construct instances of a class with the keyword
new followed by a call a constructor method of the
class.
If you do not provide a constructor, the class will
have one with no arguments and no statements by
default.
Equality Quiz 1
Is (a == b) ?
int a = 7;
int b = 7;
Is (g == h) ?
Person g = new Person(“Abebe", 26);
Person h = new Person(“Abebe", 26);
Primitives vs Objects
Two datatypes in Java: primitives and objects
g h
“Abebe" “Abebe"
26 26
Equality Quiz 2
true or false?
Person g = new Person(“Abebe", 26);
Person h = new Person(“Abebe", 26);
Person g1 = new Person(“Alemu", 23);
Person g2 = g1;
a) g == h
b) g.getAge() == h.getAge()
c) g1 == g2
d) g1.getAge() == g2.getAge();
Reference Equality
g1 == g2 because g1 and g2 hold
references to the same object
Person g1 = new Person(“Alemu", 23);
Person g2 = g1;
g1
“Alemu"
23
g2
Apple Example
class Apple {
String color;
double price;
Apple(double price) {
this("green", price);
}