5.6 Writing Methods
Enduring Understanding
Programmers use code to represent a physical object or nonphysical concept, real or imagined, by defining a class based on the attributes and/or behaviors of the object or concept.
Learning Objective
Define behaviors of an object through non-void methods with parameters written in a class.
Essential Knowledge
Methods can only access the private data and methods of a parameter that is a reference to an object when the parameter is the same type as the method’s enclosing class.
Non-void methods with parameters receive values through parameters, use those values, and return a computed value of the specified type.
It is good programming practice to not modify mutable objects that are passed as parameters unless required in the specification.
When an actual parameter is a primitive value, the formal parameter is initialized with a copy of that value. Changes to the formal parameter have no effect on the corresponding actual parameter.
When an actual parameter is a reference to an object, the formal parameter is initialized with a copy of that reference, not a copy of the object. If the reference is to a mutable object, the method or constructor can use this reference to alter the state of the object.
Passing a reference parameter results in the formal parameter and the actual parameter being aliases. They both refer to the same object.
Last updated
Was this helpful?