Overview
This lecture explains getter and setter methods in Java, demonstrating how they protect and control access to object data in a Car class.
Creating the Car Class
- Define a Car class with attributes: model (String), color (String), and price (int).
- Initialize these attributes using a constructor with matching parameters.
Public vs. Private Attributes
- Public attributes can be accessed and modified directly from outside the class.
- Changing attributes directly (e.g., model) can cause unwanted data changes.
- Use the
private
keyword to restrict direct access to attributes.
Getter Methods
- Getter methods provide read access to private fields.
- Naming convention: getAttributeName (e.g., getModel).
- Getter methods can include extra logic, such as formatting output (e.g., adding a currency symbol to price).
- Only methods within the class can access private attributes directly.
Setter Methods
- Setter methods provide write access to private fields.
- Naming convention: setAttributeName (e.g., setColor).
- Not all fields need setters (e.g., model should not be writable if it shouldn't change).
- Adding logic in setters can prevent invalid data (e.g., price can't be negative).
Example Usage
- Use getters (e.g., car.getColor()) to read values externally.
- Use setters (e.g., car.setColor("Blue")) to modify values if allowed.
- Attempting to access or modify private attributes directly will cause errors.
Additional Protections
- The
final
keyword can be used to make attributes immutable after initialization.
- Custom logic in setter methods (e.g., validation) helps maintain data integrity.
Key Terms & Definitions
- Getter Method — Makes a private field readable from outside the class.
- Setter Method — Makes a private field writable from outside the class.
- private — Java keyword restricting access to within the same class.
- final — Java keyword preventing further modification of a variable.
Action Items / Next Steps
- Practice creating classes with private attributes, and implement appropriate getter and setter methods.
- Add validation logic in setters to enforce business rules.
- Try using the final keyword to make attributes immutable where needed.