Please enable JavaScript to use CodeHS

AP Computer Science A (Mocha)

Lesson 4.6 Getter and Setter Methods

Description

In this lesson students will learn about a special type of instance method: getter and setter methods. Getter and setter methods give the client access to the private instance variables in a class. Programmers don’t want to make instance variables public because then the client has full access to them, and might accidentally do something that messes them up (for example, it doesn’t make sense to have a negative width or a negative height for a Rectangle object). Instead, programmers expose limited access to them through getter and setter methods. That way, they can allow only certain changes to the instance variables, and block other changes.


Objective

Students will be able to:

  • Describe what a getter method is
  • Describe what a setter method is
  • Explain the difference between getter and setter methods
  • Explain the purpose of getter and setter methods
  • Create getter and setter methods for their classes
  • Call getter and setter methods on an object to access the object’s private instance variables