Bird
0
0

Which of the following is the correct syntax for a setter method for a private int variable named age?

easy📝 Syntax Q12 of 15
Java - Encapsulation
Which of the following is the correct syntax for a setter method for a private int variable named age?
Aprivate void setAge(int age) { age = this.age; }
Bpublic int setAge() { return age; }
Cpublic void setAge(int age) { this.age = age; }
Dpublic int getAge(int age) { this.age = age; }
Step-by-Step Solution
Solution:
  1. Step 1: Identify setter method structure

    A setter method is public, returns void, and takes a parameter to update the private variable.
  2. Step 2: Check the parameter assignment

    The method assigns the parameter value to the instance variable using this.age = age;.
  3. Final Answer:

    public void setAge(int age) { this.age = age; } -> Option C
  4. Quick Check:

    Setter syntax = public void setVar(Type var) { this.var = var; } [OK]
Quick Trick: Setter methods are void and assign parameter to this.variable [OK]
Common Mistakes:
  • Using return type int for setter
  • Assigning instance variable to parameter instead of reverse
  • Making setter private

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes