Bird
0
0

You want to create a class Student with a private variable grade that can only be set if the value is between 0 and 100. Which is the best way to implement this using encapsulation?

hard📝 Application Q15 of 15
Java - Encapsulation

You want to create a class Student with a private variable grade that can only be set if the value is between 0 and 100. Which is the best way to implement this using encapsulation?

AMake <code>grade</code> public and check the value before assigning
BMake <code>grade</code> static and assign directly
CUse a protected <code>grade</code> variable and no setter
DUse a private <code>grade</code> variable with a setter that validates the value
Step-by-Step Solution
Solution:
  1. Step 1: Understand encapsulation for validation

    Encapsulation allows controlling how variables are set by using private variables and setters with checks.
  2. Step 2: Choose the best practice

    Using a private variable with a setter that validates the input ensures grade stays between 0 and 100.
  3. Final Answer:

    Use a private grade variable with a setter that validates the value -> Option D
  4. Quick Check:

    Setters with validation keep data safe [OK]
Quick Trick: Validate data inside setter to protect private variables [OK]
Common Mistakes:
  • Making variables public and trusting external code
  • Skipping validation in setter
  • Using static which shares data across all instances

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes