Bird
0
0

You want to allow access to a variable only to subclasses, even if they are in different packages, but not to other classes in the same package. How can you achieve this in Java?

hard📝 Application Q8 of 15
Java - Packages and Access Control
You want to allow access to a variable only to subclasses, even if they are in different packages, but not to other classes in the same package. How can you achieve this in Java?
ADeclare the variable as public and restrict access by convention
BDeclare the variable as protected and put subclasses in different packages
CDeclare the variable as protected and put subclasses in the same package
DDeclare the variable as private and provide protected getter method
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected access scope

    Protected allows access to subclasses and all classes in the same package, so it cannot restrict same-package classes.
  2. Step 2: Use private with protected getter

    Declaring variable private hides it from all, but a protected getter allows subclasses access only, excluding other same-package classes.
  3. Final Answer:

    Declare the variable as private and provide protected getter method -> Option D
  4. Quick Check:

    Private + protected getter limits access to subclasses only [OK]
Quick Trick: Use private variable + protected getter for subclass-only access [OK]
Common Mistakes:
  • Thinking protected hides from same-package classes
  • Using public and relying on convention
  • Ignoring access modifier combinations

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes