Introduction: 5.4.0

  • Instance variables are usually private
    • Instead use public methods to provide safe access
  • accessor methods
    • get methods or getters
    • 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 called
  • toString() is overridden to provide a string representation of an object
    • typically shows values of member variables
  • if System.out.print or System.out.println are passed an object, the toString method is called on that object.