Bird
0
0

Find the problem in this code snippet:

medium📝 Debug Q7 of 15
Java - Packages and Access Control
Find the problem in this code snippet:
package pkg1;
public class Parent {
    protected void show() {
        System.out.println("Parent show");
    }
}

package pkg2;
import pkg1.Parent;
public class Child {
    public static void main(String[] args) {
        Parent p = new Parent();
        p.show();
    }
}
ANo problem, code runs fine
BCannot call protected method from non-subclass in different package
CMissing override annotation
DMethod show() must be public
Step-by-Step Solution
Solution:
  1. Step 1: Understand protected method access

    Protected methods are accessible within same package or subclasses in other packages.
  2. Step 2: Analyze code context

    Class Child is not a subclass and is in a different package, so calling p.show() causes access error.
  3. Final Answer:

    Cannot call protected method from non-subclass in different package -> Option B
  4. Quick Check:

    Protected method access limited outside package to subclasses [OK]
Quick Trick: Protected methods need subclass or same package to access [OK]
Common Mistakes:
  • Assuming protected methods are public
  • Ignoring subclass requirement outside package
  • Expecting code to compile without subclass

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes