Accessor Methods
Introduction: 5.4.0
- Instance variables are usually private
- Instead use public methods to provide safe access
accessor methods
get methods
orgetters
- allow ways to get a value of instance variables to get the value from outside the class
- return the instance variable’s value
public class House {
private String address;
public String getAddress() {
return address;
}
}
primitive vs reference type returns
- primitive type return values are a copy of the value
return by value
- reference type return values are a copy of the object reference
- these refer to the actual object in the class!
toString(): 5.4.1
- returns a string description of the instance variables of an object
- called automatically when printing
Summary: 5.4.3
- An accessor method returns the value of a member variable
- makes it accessible outside of the class
- a non-void method returns a value
- the header includes the return type instead of void
- accessor methods that return primitives use “return by value”
- returns a copy
- accessor methods that return object references copy the reference, not the object
- the reference still points to the original object
return
is used to return the flow of control to the point after the method/constructor was calledtoString()
is overridden to provide a string representation of an object- typically shows values of member variables
- if
System.out.print
orSystem.out.println
are passed an object, thetoString
method is called on that object.
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.