Java Getter and Setter Methods

Aug 26, 2025

Overview

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

Creating a Java Class and Attributes

  • A Car class is created with attributes: model (String), color (String), and price (int).
  • A constructor initializes these attributes using parameters.
  • Objects can be created from the Car class and their attributes printed.

Access Modifiers and Data Protection

  • By default, attributes are publicly accessible, allowing direct reading and modification.
  • Changing an attribute, like model, is easy if attributes are public, which may not be desired.
  • Setting attributes as private restricts access from outside the class.

Getter Methods (Read Access)

  • Getter methods allow reading the values of private attributes.
  • A getter methodโ€™s naming convention is getAttributeName().
  • Example: public String getModel() { return this.model; }
  • Getters can include additional logic, such as formatting or adding currency symbols.

Setter Methods (Write Access)

  • Setter methods allow controlled modification of private attributes.
  • Naming convention: setAttributeName(), with a void return type.
  • Example: public void setColor(String color) { this.color = color; }
  • Setters can include validation logic, e.g., price cannot be negative.

Controlling Readability and Writability

  • If an attribute should not be modified after construction (e.g., model), do not provide a setter for it.
  • Use the final keyword to make an attribute immutable for extra security.

Example of Additional Logic in Setters

  • In a setter for price, check if the new value is negative. If so, output an error message and do not update the attribute.

Key Terms & Definitions

  • Getter Method โ€” A method that returns the value of a private attribute, making it readable.
  • Setter Method โ€” A method that changes the value of a private attribute, making it writable.
  • Private Access Modifier โ€” Keyword (private) that restricts attribute access to within the class.
  • Final Keyword โ€” Keyword that prevents an attribute from being changed after initialization.

Action Items / Next Steps

  • Practice creating getter and setter methods for a new class.
  • Add validation logic to setters to enforce rules on attribute values.