1Z0-803 · Question #169
Given: package handy.dandy; public class Keystroke { public void typeExclamation() { System.out.println("!"); } } And 1. package handy; 2. public class Greet { 3. public static void main(String[] args
The correct answer is C. line 6 replaced with handy.dandy.Keystroke stroke = new handy.dandy.Keystroke(); E. import handy.dandy.*; added after line 1 F. import handy.dandy.Keystroke; added after line 1. This question tests the understanding of Java package and import mechanisms for accessing classes defined in different packages.
Question
Options
- Aline 6 replaced with handy.dandy.Keystroke stroke = new Keystroke();
- Bline 6 replaced with handy.*.Keystroke stroke = new Keystroke();
- Cline 6 replaced with handy.dandy.Keystroke stroke = new handy.dandy.Keystroke();
- Dimport handy.*; added before line 1
- Eimport handy.dandy.*; added after line 1
- Fimport handy.dandy.Keystroke; added after line 1
- Gimport handy.dandy.Keystroke.typeExclamation(); added before line 1
How the community answered
(42 responses)- A7% (3)
- B2% (1)
- C74% (31)
- D14% (6)
- G2% (1)
Why each option
This question tests the understanding of Java package and import mechanisms for accessing classes defined in different packages.
While the type `handy.dandy.Keystroke` is qualified, the constructor call `new Keystroke()` remains unqualified and would look for `Keystroke` within the `handy` package, leading to a compilation error.
The syntax `handy.*.Keystroke` is an invalid package or class reference; the wildcard `*` is only permitted in `import` statements, not in class declarations.
Fully qualifying both the class type and the constructor call with its complete package path `handy.dandy.Keystroke` resolves the class location explicitly, allowing the code to compile.
Importing `handy.*` only makes classes directly within the `handy` package available, not classes in its subpackages like `handy.dandy`, thus `Keystroke` remains unresolvable.
Adding `import handy.dandy.*;` after the package declaration makes all classes within the `handy.dandy` package, including `Keystroke`, accessible by their simple names, enabling compilation.
Adding `import handy.dandy.Keystroke;` after the package declaration specifically imports the `Keystroke` class, making it accessible by its simple name without needing full qualification.
The syntax `import handy.dandy.Keystroke.typeExclamation();` is invalid for importing classes; imports are for types (classes, interfaces) not individual methods.
Concept tested: Java package and import statements
Source: https://docs.oracle.com/javase/tutorial/java/package/usepkgs.html
Topics
Community Discussion
No community discussion yet for this question.