Java Getters and Setters Overview

Aug 26, 2025

Overview

This lecture explains getter and setter methods in Java, showing how they control and protect access to object data in a class.

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.
  • Attributes are initially public, allowing direct access and modification.

Using Private Access Modifier

  • Add the private keyword to attributes to restrict direct access from outside the class.
  • Private attributes cannot be directly read or modified from outside the class.

Getter Methods

  • Getter methods allow reading private fields from outside the class.
  • Naming convention: getAttributeName(), e.g., getModel().
  • Return the value of the corresponding private attribute.
  • Getters can include additional logic, such as formatting or validation.

Setter Methods

  • Setter methods allow writing (updating) private fields from outside the class.
  • Naming convention: setAttributeName(newValue), e.g., setColor(String color).
  • Assign the new value to the corresponding attribute.
  • Setters can include validation logic, like preventing a negative price.

Controlling Access with Getters and Setters

  • Only implement setters for attributes you want to allow modification (e.g., color and price, but not model).
  • Do not create a setter for read-only attributes to keep them immutable.
  • Use the final keyword for attributes that should never change (stronger immutability).

Example of Validation in Setters

  • Within a setter, check for invalid input (e.g., price < 0) and prevent changes if validation fails.
  • Output an error message if invalid data is provided; otherwise, update the attribute.

Key Terms & Definitions

  • Getter Method — A method that returns the value of a private attribute (read access).
  • Setter Method — A method that sets or updates the value of a private attribute (write access).
  • Private Attribute — An attribute declared with the private keyword, restricting access to within the class.
  • Constructor — A special method called to initialize an object when it is created.
  • Final Keyword — Prevents an attribute from being modified after its initial assignment.

Action Items / Next Steps

  • Practice writing getter and setter methods in a new Java class.
  • Experiment with applying validation logic in setter methods.
  • Try making some attributes final and observe how it affects mutability.