Bird
0
0

You want to create a Java class with a public method that can be called from any other class, but the class itself should only be accessible within its package. Which of the following is correct?

hard📝 Application Q15 of 15
Java - Packages and Access Control
You want to create a Java class with a public method that can be called from any other class, but the class itself should only be accessible within its package. Which of the following is correct?
ADeclare both the class and method as public.
BDeclare the class as private and the method as public.
CDeclare the class as public and the method as private.
DDeclare the class without public and the method as public.
Step-by-Step Solution
Solution:
  1. Step 1: Understand class access modifiers

    Classes without public are package-private, so accessible only within the package.
  2. Step 2: Understand method access modifiers

    Methods declared public inside a package-private class are accessible from other classes in the same package.
  3. Step 3: Analyze options

    Declare the class without public and the method as public. matches the requirement: class package-private, method public. Declare both the class and method as public. makes class public (accessible everywhere). Declare the class as public and the method as private. hides method. Declare the class as private and the method as public. is invalid because classes cannot be private.
  4. Final Answer:

    Declare the class without public and the method as public. -> Option D
  5. Quick Check:

    Class package-private + public method = accessible in package [OK]
Quick Trick: Class without public is package-private; method public means accessible inside package [OK]
Common Mistakes:
  • Thinking class can be private
  • Assuming public class needed for public method
  • Confusing method access with class access

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes