02 OOP Concepts
02 OOP Concepts
OOP Concepts
Objects
2
Data types
3
Object types
class:
Basic building block of Java programs (what we have seen so far)
AND
Data types for objects
4
Example object types
Theoretical examples:
A class Person could represent objects that store a name,
height, weight, hair color, IQ, etc…
A class Laptop could represent objects that store speed,
screen size, color, dimensions, brand, etc…
5
Point objects
6
Point object
7
Constructing objects
Examples:
Point p = new Point(7, -4);
Scanner console = new Scanner(System.in);
Examples:
Point p1 = new Point(5, -2);
Point p2 = new Point();
9
Representing objects
int x = 7;
X: 7
Representing objects
p:
x: y:
7 3
Variable,
with slot in Reference, a
memory Data, in another
pointer to the part of memory
object’s data
References
p:
x: y:
7 3
Variable, with
slot in
Reference, a
memory Data, in another
pointer to the
part of memory
object’s data
Constructing an object
p1: x: 7 y: 2
13
null objects
Point p1 = null;
p1:
14
Calling methods on objects
Examples:
String s1 = “Homey da Clown”;
String s2 = “Bubbles the clown”;
System.out.println(s1.length()); // prints 14
System.out.println(s2.length()); // prints 17
15
Calling methods on objects
Examples:
Point p0 = new Point(0, 0);
Point p1 = new Point(7, 3);
Point p2 = new Point(2, -2);
System.out.println(p1.distance(p0)); // 7.62
System.out.println(p2.distance(p0)); // 2.83
16
Dereferencing
Point p = null;
p.x = 7; // Error!
p.setLocation(0,0); // Error!
20
instances
Each instance has its own local copy of the state and
behavior defined in the class template.
Same as:
System.out.println("p: " + p.toString());
Every class has a toString(), even if it isn't in your code.
The default is the class's name and a hex (base-16) hash-code:
Point@9e8c34
toString() implementation