Chapter 2 Flashcards
Inner part of class consist of____
- Fields- store date persistently w/i an object
- Constructors- ensures that an object is set up properly when it is first created
- Methods- implement the behavior of an object; provide its functionality
What is another name for fields?
instance variables
Field pattern
- usually start with reserved word: private
- they include a type name (such as int, String, Person, etc.)
- include a user-chosen name for the field variable
- end with semicolon
Fields
- Store values for an object
- Define state of object
- Use inspect to view state
- some values change often
- some change raraely
- always define fields to be private
ie:
private int price;
constructors
- initialize the fields
- have same name as class
- close association w/fields
- store initial values into the fields
- external parameters values for this
For these constructors, why isn’t price set to 0?
{
price = cost;
balance = 0;
total = 0;
}
Because we don’t know what the ticket price will be for this project since it’s entered externally.
Passing data via parameter
- parameters are another sort of variable
- used to hold data
- temporary messenger carrying data originating externally
What is formal parameter vs actual parameter
formal is parameter names such as cost in
TicketMachine(int cost)
while actual is the user supplied value like 500 if user entered that
Assignment
- values are stored into fields & other variables via assignment statements
ie:
variable = expression;
price = cost; - a variable stores a single value, so any previous value is lost
- types must match
Methods
- yellow boxes
- 2 parts: header & body
- always has parenthesis and no semicolons at end
method header
- provides method’s signature
- tells us:
method name
parameters it takes
whether it returns a result
it’s visibility to objects of other classes
Method body
- Encloses the method’s statements with curly brackets
- contain:
declarations- used to create additional, temp variable space
statements- describe actions of the method - a set of declarations and statements b/t curly brackets is a block
Accessor (get) Method
- always has non void return type
- returns value (result) of the type given in header
- contains return statement
T or F: returning is the same as printing
F: returning is not printing!
Returning a value
- some info passed internally b/t 2 different parts of a program
- 1 part requested info from object via method call & return value is the way the object has of passing the info back to caller
Mutator method
- Changes state of object- mutate
- achieved through changing the value of 1 or more fields
typically contain assignment statements
often receive parameters
What kind of method is this code:
Public int getPrice()
{
return price;
}
Accessor