Cheat Sheet
This cheat sheet contains the most important takeaways that lead up to section seven.
Definitions
-
Class: blueprint from which you can create objects.
-
Object: an object is a thing that you can see or describe.
-
Field: class variable that describes an object.
-
Action: method (function) that represents what the object can do.
-
Constructor: runs when you create a
new
object.- Purpose: update every field of the newly created object.
-
this
: refers to the current object that's calling the constructor or method.- Purpose: useful when fields and parameters have conflicting names.
-
Copy Constructor: runs when you create an object.
- Purpose: copy every value from a
source
object into anew
object.
- Purpose: copy every value from a
-
Getter: method (function) that returns a copy of a
private
field's value. -
Setter: method (function) that updates the value of a
private
field. -
toString
: method that returns aString
representation of every field in an object.- Purpose: When you print an object, Java internally calls the
toString
method.
- Purpose: When you print an object, Java internally calls the
public
vs. private
-
public
: provides public access to a field or method from anywhere.- Constructors and methods tend to be
public
.
- Constructors and methods tend to be
-
private
: prevents direct access of a field or method outside of its class.- To protect the state of an object, fields tend to be
private
.
- To protect the state of an object, fields tend to be
The Big Three
If a class
has fields, you need to add:
-
Constructor -- to update the fields of a
new
object. -
Getters -- to get the value of a
private
field. -
Setters -- to set the value of a
private
field.
Reference Traps
The state of a variable should not change because you updated another.