1Z0-811 · Question #34
Given these class definitions: class MyClassA { } public class MyClassB { } class MyClassC extends Object { } class MyClassD { public static void main (String [] args) { } } Which class or classes…
The correct answer is D. only MyClassB and MyClassD. Important note on this question: The given answer D appears to be incorrect. In standard Java, all four classes compile (Answer C), assuming they are each in properly named files or together in a file named MyClassB.java. Here's why each class is valid: MyClassA - class…
Question
Options
- Aonly MyClassB, MyClassC, and MyClassD
- Bonly MyClassB
- CMyClassA, MyClassB, MyClassC, and MyClassD
- Donly MyClassB and MyClassD
How the community answered
(43 responses)- A7% (3)
- B5% (2)
- C14% (6)
- D74% (32)
Explanation
Important note on this question: The given answer D appears to be incorrect. In standard Java, all four classes compile (Answer C), assuming they are each in properly named files or together in a file named MyClassB.java.
Here's why each class is valid:
- MyClassA -
class MyClassA { }is a perfectly valid package-private class. No body or access modifier is required to compile. - MyClassB -
public class MyClassB { }compiles, provided the source file is namedMyClassB.java(the key rule: apublicclass must live in a file matching its name). - MyClassC -
class MyClassC extends Object { }compiles. Every Java class implicitly extendsObject, and making that explicit is redundant but not a compile error. - MyClassD - Compiles. Having a
mainmethod is irrelevant to compilation - it only matters for execution.
The rule this question is actually testing: a public top-level class must be in a .java file whose name exactly matches the class name. If these were all in a single file not named MyClassB.java, then MyClassB would fail - but the others would still compile.
Memory tip: "Public = precise filename." Only public classes carry a naming constraint. Non-public classes are flexible about which file they live in, and extends Object is always legal (just noise).
If this is from an official prep guide, I'd recommend verifying against the Java Language Specification or running the code - the correct answer by the JLS is C.
Topics
Community Discussion
No community discussion yet for this question.