Java Getters and Setters

Aug 26, 2025

Overview

This lecture explains getter and setter methods in Java, demonstrating how they help control and protect access to object data through a Car class example.

Creating the Car Class

  • A Car class is defined with attributes: model (String), color (String), and price (int).
  • A constructor initializes these attributes with parameters.

Public vs. Private Attributes

  • Public attributes can be accessed and modified directly from outside the class.
  • To prevent unwanted changes, use the private access modifier for attributes.

Getter Methods

  • Getter methods provide controlled access to private fields (read-only).
  • Naming convention: getAttributeName() returns the field value.
  • Additional logic (like formatting) can be added within getters.

Setter Methods

  • Setter methods allow controlled modification of private fields (write access).
  • Naming convention: setAttributeName(value) assigns a new value to the field.
  • Not all attributes need setters (e.g., model should not change once set).

Making Attributes Read-Only or Write-Only

  • Omit the setter to make an attribute read-only.
  • Add the final keyword to prevent even setter modifications.

Adding Validation Logic

  • Setters can include checks (e.g., price must not be negative).
  • If validation fails, show an error and skip updating the value.

Example Usage

  • Getter methods are used to retrieve values: car.getColor(), car.getModel(), car.getPrice().
  • Setter methods update values when allowed: car.setColor("blue"), car.setPrice(5000).

Key Terms & Definitions

  • Getter Method — A function that returns the value of a private attribute (makes it readable).
  • Setter Method — A function that sets the value of a private attribute (makes it writable).
  • Private Attribute — A variable only accessible within its own class.
  • Final Keyword — Prevents a variable from being modified after initialization.
  • Validation — Logic in setters to ensure only acceptable data is set.

Action Items / Next Steps

  • Practice creating a Java class with private attributes, getters, and setters.
  • Experiment adding validation logic in setter methods.
  • Review Java concepts of access modifiers and encapsulation.