Bird
0
0

You have a package tools with classes:

hard📝 Application Q15 of 15
Java - Packages and Access Control
You have a package tools with classes:
class Helper {
    void assist() {
        System.out.println("Helping...");
    }
}

public class Tool {
    public static void main(String[] args) {
        Helper h = new Helper();
        h.assist();
    }
}

You want to allow only classes inside tools to use Helper and its assist() method, but prevent access from outside. Which is the best way to achieve this?
AMake Helper and assist() public.
BUse protected for Helper and assist().
CMake Helper and assist() private.
DKeep Helper and assist() with default access (no keyword).
Step-by-Step Solution
Solution:
  1. Step 1: Understand access goals

    You want Helper and assist() accessible only inside the same package (tools) and hidden outside.
  2. Step 2: Match access modifiers to goals

    Default access (no keyword) restricts access to the same package only, which fits the requirement. Public allows all access, private restricts to the class only, and protected allows subclasses and package access.
  3. Final Answer:

    Keep Helper and assist() with default access (no keyword). -> Option D
  4. Quick Check:

    Default access = package-only visibility [OK]
Quick Trick: Default access hides from outside packages [OK]
Common Mistakes:
  • Using public which exposes to all packages
  • Using private which hides even inside package
  • Using protected which allows subclass access outside package

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes