Bird
0
0

Which of the following is the correct syntax to provide access to a private variable age in a class?

easy📝 Syntax Q3 of 15
Java - Encapsulation

Which of the following is the correct syntax to provide access to a private variable age in a class?

Aint getAge() { return age; }
Bpublic int getAge() { return age; }
Cprivate int getAge() { return age; }
Dpublic void age() { return age; }
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct getter method syntax

    A getter method should be public to allow outside access and return the private variable.
  2. Step 2: Check each option

    public int getAge() { return age; } is public, returns int, and returns age correctly. Others are either private, missing return type, or wrong method signature.
  3. Final Answer:

    public int getAge() { return age; } -> Option B
  4. Quick Check:

    Getter method must be public and return variable [OK]
Quick Trick: Getters are public methods returning private variables [OK]
Common Mistakes:
  • Making getter methods private
  • Using void return type for getters
  • Naming getter methods incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes