Bird
0
0

Examine the code below:

medium📝 Debug Q6 of 15
Java - Packages and Access Control
Examine the code below:
package pkgA;
public class Base {
    protected String message = "Hello";
}

package pkgB;
import pkgA.Base;
public class Demo {
    public static void main(String[] args) {
        Base b = new Base();
        System.out.println(b.message);
    }
}

What is the issue with this code?
AProtected members cannot be of type String
BCannot import class from another package
CCannot access protected member from non-subclass in different package
DNo issues; code will compile and run successfully
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected access rules

    Protected members are accessible within the same package or by subclasses in other packages.
  2. Step 2: Analyze the code

    Class Demo is not a subclass of Base and is in a different package, so it cannot access message.
  3. Step 3: Identify the error

    Accessing b.message causes a compile-time error due to protected access restrictions.
  4. Final Answer:

    Cannot access protected member from non-subclass in different package -> Option C
  5. Quick Check:

    Protected access requires subclass or same package [OK]
Quick Trick: Protected access denied outside package without subclass [OK]
Common Mistakes:
  • Assuming protected is like public across packages
  • Ignoring subclass requirement for access outside package
  • Confusing import errors with access errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes