Java Getters and Setters

Aug 26, 2025

Overview

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

Creating a Car Class

  • Define a Car class with attributes: String model, String color, and int price.
  • Use a constructor to initialize model, color, and price attributes.
  • Create a Car object by providing specific values for model, color, and price.

Attribute Access and Encapsulation

  • By default, class attributes are publicly accessible and can be changed directly.
  • Use the private keyword to restrict direct access to class attributes.
  • Private attributes cannot be accessed or modified directly from outside the class.

Getter Methods

  • Getter methods allow reading of private attributes.
  • Convention: method name starts with get followed by the attribute name (e.g., getModel).
  • Example: public String getModel() { return this.model; }
  • Getter methods can include additional logic, such as formatting or validation.

Setter Methods

  • Setter methods allow controlled modification of private attributes.
  • Convention: method name starts with set followed by the attribute name (e.g., setColor).
  • Example: public void setColor(String color) { this.color = color; }
  • Setter methods can include logic to validate new values (e.g., reject negative prices).

Readable vs Writable Attributes

  • Some attributes (like model) should be readable but not writable; omit the setter method to prevent changes.
  • Use the final keyword if an attribute should not be modified after initialization.

Example of Enhanced Setter Logic

  • Include checks in setter methods to prevent invalid values (e.g., disallow negative prices in setPrice).

Key Terms & Definitions

  • Getter Method — A method that returns the value of a private attribute (makes a field readable).
  • Setter Method — A method that updates the value of a private attribute (makes a field writable).
  • Private Attribute — A class variable declared with the private keyword, hidden from outside the class.
  • Encapsulation — The practice of restricting access to internal object data using methods.
  • Final — A keyword used to make an attribute unchangeable after initialization.

Action Items / Next Steps

  • Practice creating classes with private attributes and implement getter and setter methods.
  • Add validation logic to setter methods for data integrity.
  • Review Java documentation on encapsulation, getters, and setters.