Bird
0
0

You want to protect a class's sensitive data but allow controlled updates only if the new value is positive. How would you implement this using data hiding in Java?

hard📝 Application Q15 of 15
Java - Encapsulation
You want to protect a class's sensitive data but allow controlled updates only if the new value is positive. How would you implement this using data hiding in Java?
AMake the variable public and check the value before assigning it outside the class
BMake the variable private and write a setter that updates only if the value is positive
CMake the variable protected and allow direct access in subclasses
DUse a public variable and no setter method
Step-by-Step Solution
Solution:
  1. Step 1: Use private variable for data hiding

    Keep the sensitive variable private to prevent direct external access.
  2. Step 2: Implement setter with condition

    Write a setter method that updates the variable only if the new value is positive, ensuring controlled updates.
  3. Final Answer:

    Make the variable private and write a setter that updates only if the value is positive -> Option B
  4. Quick Check:

    Private variable + conditional setter = safe updates [OK]
Quick Trick: Use private variable with conditional setter method [OK]
Common Mistakes:
  • Making variable public and trusting external checks
  • Using protected instead of private for sensitive data
  • Not validating data in setter method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes