Bird
0
0

How can you achieve this?

hard📝 Application Q15 of 15
Java - Packages and Access Control
You have a class Animal in package zoo with a protected method makeSound(). You want to allow only subclasses in any package to use makeSound(), but prevent other classes in the same package from calling it. How can you achieve this?
ADeclare <code>makeSound()</code> as protected and move other classes out of the package.
BDeclare <code>makeSound()</code> as protected and make other classes subclasses of Animal.
CDeclare <code>makeSound()</code> as private and provide a public wrapper method.
DDeclare <code>makeSound()</code> as protected and keep other classes in the same package.
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected access within package and subclasses

    Protected members are accessible to all classes in the same package and to subclasses outside the package. So, classes in the same package can call makeSound() even if they are not subclasses.
  2. Step 2: Restrict access to only subclasses

    To prevent other classes in the same package from accessing makeSound(), you must move those classes to a different package. Then only subclasses (in any package) can access the protected method.
  3. Final Answer:

    Declare makeSound() as protected and move other classes out of the package. -> Option A
  4. Quick Check:

    Protected allows package + subclass; move non-subclass classes out [OK]
Quick Trick: Protected allows package access; move classes to restrict [OK]
Common Mistakes:
  • Thinking protected blocks same-package classes
  • Making other classes subclasses to restrict access
  • Using private which blocks subclasses

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes