1Z0-819 · Question #21
Given: ``java package A; class Test { String name; public Test (String name) { this.name = name; } public String toString() { return name; } } ` and `java package B; import A.Test; public class Main…
The correct answer is C. Student. Option C is actually not the correct answer here - this appears to be a trick question where the stated answer is wrong. The real answer is E (Compilation fails), because Test in package A is declared without an access modifier, making it package-private by default…
Question
package A;
class Test {
String name;
public Test (String name) {
this.name = name;
}
public String toString() {
return name;
}
}
and
package B;
import A.Test;
public class Main {
public static void main(String[] args) {
Test test = new Test("Student");
System.out.println(test);
}
}
What is the result?Options
- Anull
- Bnothing
- CStudent
- Djava.lang.IllegalAccessException is thrown.
- ECompilation fails.
How the community answered
(45 responses)- A4% (2)
- B2% (1)
- C71% (32)
- D7% (3)
- E16% (7)
Explanation
Option C is actually not the correct answer here - this appears to be a trick question where the stated answer is wrong. The real answer is E (Compilation fails), because Test in package A is declared without an access modifier, making it package-private by default. Package-private classes are only accessible within the same package, so import A.Test in package B causes a compile-time error - the compiler cannot see the Test class at all.
- A (null) is wrong because
nameis set in the constructor; there's no null-return scenario to reach. - B (nothing) is wrong for the same reason - if the code ran,
toString()returnsname, which is"Student". - C (Student) would be correct only if
Testwere declaredpublic class Test- the code logic itself is fine, but access never gets that far. - D (IllegalAccessException) is a runtime exception; this is a compile-time visibility issue, not a reflection-based runtime one.
Memory tip: In Java, missing access modifier = package-private. Always scan class declarations for public - if it's absent and the class is used cross-package, the code won't compile. Think: "No modifier, no export."
Topics
Community Discussion
No community discussion yet for this question.