Back to the 2019 paper

Module III: Basics of Web Programming

20197m

Describe how the following features of Java relate to the behavior of accessor and mutator methods:

(i) Fields
(ii) Local variables
(iii) Parameters
(iv) Return values
(v) Visibility modifiers

Illustrate each with brief code samples.

Worked SolutionAI Assisted

Answer: Relationship of Java Language Features with Accessor and Mutator Methods

1. Introduction to Accessor and Mutator Methods

In Java Object-Oriented Programming, Encapsulation is achieved by keeping class data hidden and providing controlled access through:

  • Accessor Methods (Getters): Public methods that retrieve/read the internal state of an object without modifying it.
  • Mutator Methods (Setters): Public methods that modify/update the internal state of an object, often performing data validation.
[ External Caller ] ---> getAge() [Accessor] ---> Reads (Returns field value)
                    ---> setAge(21) [Mutator] ---> Validates & Updates Private Field

2. Detailed Relationship with Java Features

(i) Fields (Instance Variables)

  • Role: Fields hold the persistent state and data of the object.
  • Relationship: To protect fields from direct unauthorized access or corruption, they are declared private. Accessors read from these fields, while mutators write to them.
public class Account {
    private double balance; // Private instance field
}

(ii) Local Variables

  • Role: Variables declared inside the body of a method that exist only on the call stack for the duration of method execution.
  • Relationship: Mutators and accessors use local variables to perform temporary calculations, formatting, or validation checks before updating or returning field values.
public String getFormattedBalance() {
    String currencySymbol = "Rs. "; // Local variable
    return currencySymbol + this.balance;
}

(iii) Parameters (Formal Arguments)

  • Role: Input variables defined in the method signature that receive values passed by the caller.
  • Relationship: Mutator methods accept parameters representing the new desired state. The this keyword is used to distinguish the instance field from the method parameter when they share the same name (shadowing).
public void setBalance(double balance) { // 'balance' is a parameter
    if (balance >= 0) {
        this.balance = balance; // 'this.balance' is the field; 'balance' is the parameter
    }
}

(iv) Return Values

  • Role: The value and data type sent back to the caller when a method completes.
  • Relationship:
    • Accessors: Must have a non-void return type matching or widening the field's data type (e.g., public double getBalance()).
    • Mutators: Typically have a void return type, or return a boolean to indicate if the mutation/validation succeeded.
public double getBalance() {
    return this.balance; // Non-void return value
}

(v) Visibility Modifiers (private, public, protected)

  • Role: Specify access control boundaries and information hiding.
  • Relationship:
    • Fields: Declared private to restrict direct access from outside classes.
    • Accessors & Mutators: Declared public to expose a safe, controlled interface to external callers.
private int age;             // Hidden from outside world
public int getAge() { ... }  // Publicly accessible read
public void setAge(int a) {  // Publicly accessible validated write
    if (a > 0 && a < 120) this.age = a;
}

3. Comprehensive Integrated Code Example

public class StudentProfile {
    // (i) & (v) Private Instance Fields
    private String studentName;
    private int studentAge;

    // (iv) & (v) Public Accessor (Getter) with Return Value
    public String getStudentName() {
        return this.studentName;
    }

    // (iii), (iv) & (v) Public Mutator (Setter) with Parameter
    public void setStudentName(String studentName) {
        // (ii) Local variable used for validation
        boolean isValid = (studentName != null && !studentName.trim().isEmpty());
        if (isValid) {
            this.studentName = studentName.trim();
        }
    }

    // Accessor for Age
    public int getStudentAge() {
        return this.studentAge;
    }

    // Mutator for Age with validation logic
    public boolean setStudentAge(int studentAge) {
        if (studentAge >= 17 && studentAge <= 60) {
            this.studentAge = studentAge;
            return true; // (iv) Boolean return value indicating success
        }
        return false;
    }
}

Similar questions