Java Getter and Setter Methods

Aug 26, 2025

Overview

This lecture explains getter and setter methods in Java, demonstrating how they protect object data and control access or modification of class attributes.

Creating a Car Class

  • Define a Car class with attributes: model (String), color (String), and price (int).
  • Use a constructor to initialize model, color, and price when creating a Car object.
  • Car attributes are public by default, allowing direct access and modification.

Using Private Attributes

  • Make class attributes private (private String model, etc.) to restrict direct access from outside the class.
  • Directly accessing private attributes from outside the class results in access errors.

Getter Methods

  • Getter methods allow reading private attributes using a public method (e.g., getModel()).
  • Getters typically follow the naming convention getAttributeName.
  • Getter methods return the current value of a private attribute.
  • Additional logic, such as formatting, can be added to getter methods (e.g., returning price with a currency symbol).

Setter Methods

  • Setter methods allow modifying private attributes using a public method (e.g., setColor(String color)).
  • Setters follow the naming convention setAttributeName.
  • Only include setter methods for attributes you want to allow changes (e.g., color and price, but not model).
  • Add logic to setter methods to validate changes, such as preventing negative prices.

Controlling Attribute Accessibility

  • Attributes without setter methods are read-only from outside the class.
  • Adding the final keyword to an attribute makes it immutable after initialization.
  • Setters can be omitted to prevent unwanted changes to sensitive data.

Key Terms & Definitions

  • Getter Method — A public method to retrieve (read) the value of a private class attribute.
  • Setter Method — A public method to update (write) the value of a private class attribute.
  • Private Attribute — A class variable declared with private, restricting direct external access.
  • final Keyword — Prevents a variable from being reassigned after it is set.
  • Constructor — Special method to initialize objects when they are created.

Action Items / Next Steps

  • Practice creating a Java class with private attributes, getters, and setters.
  • Add logic to setter methods for attribute validation.
  • Experiment with omitting setters for read-only attributes and using final for immutability.