Packages, access modifiers, and top-level classes: will this code compile? package foo; import java.util.Vector; // Line 2 private class MyVector extends Vector { int i = 1; // Line 5 public MyVector() { i = 2; } } public class MyNewVector extends MyVector { public MyNewVector() { i = 4; // Line 15 } public static void main (String args[]) { MyVector v = new MyNewVector(); // Line 19 } }

Difficulty: Easy

Correct Answer: Compilation will fail at line 3.

Explanation:


Introduction / Context:
Here we test Java's rules for top-level class access modifiers within a package. Only public or package-private (no modifier) are allowed for top-level classes; private and protected are illegal at the top level.


Given Data / Assumptions:

  • File declares package foo;.
  • MyVector is declared as private class MyVector at top level (Line 3).
  • MyNewVector is a public class extending MyVector.


Concept / Approach:
The Java Language Specification allows only two choices for top-level class visibility: public or no modifier (package-private). Any attempt to mark a top-level class as private is a compile-time error.


Step-by-Step Solution:
Encounter private class MyVector extends Vector at line 3. Compiler flags: “modifier private not allowed here” (or similar message). Compilation halts; subsequent lines are not relevant.


Verification / Alternative check:
Change private to no modifier (package-private) or move MyVector to a nested class inside another type if private scope is required.


Why Other Options Are Wrong:
There is nothing illegal at lines 5, 15, or 19 once line 3 is fixed. The failure is specifically due to the top-level private modifier.


Common Pitfalls:
Confusing inner class modifiers with top-level class modifiers; forgetting that only one public top-level class per file is allowed (matching file name).


Final Answer:
Compilation will fail at line 3.

More Questions from Objects and Collections

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion