Bird
0
0

Consider two classes in different packages:

medium📝 Predict Output Q5 of 15
Java - Packages and Access Control
Consider two classes in different packages:
package pkg1;
class A {
    void display() { System.out.println("Display A"); }
}

package pkg2;
import pkg1.A;
class B {
    public static void main(String[] args) {
        A a = new A();
        a.display();
    }
}

What will happen when class B is compiled?
ACompilation error: class A is not public
BCompilation error: display() is not visible
CRuntime error
DDisplay A
Step-by-Step Solution
Solution:
  1. Step 1: Check class A access modifier

    Class A has default access (no modifier), so it is package-private and not visible outside pkg1.
  2. Step 2: Check usage in pkg2

    Class B tries to import and use A from pkg1, which is not allowed because A is not public.
  3. Final Answer:

    Compilation error: class A is not public -> Option A
  4. Quick Check:

    Default class access restricts visibility outside package [OK]
Quick Trick: Default class not visible outside its package [OK]
Common Mistakes:
  • Assuming default class is public
  • Confusing method access with class access
  • Expecting runtime error instead of compile error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes