nerdexam
Oracle

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…

Java Basics

Question

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 compile?

Options

  • Aonly MyClassB, MyClassC, and MyClassD
  • Bonly MyClassB
  • CMyClassA, MyClassB, MyClassC, and MyClassD
  • Donly MyClassB and MyClassD

How the community answered

(43 responses)
  • A
    7% (3)
  • B
    5% (2)
  • C
    14% (6)
  • D
    74% (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 named MyClassB.java (the key rule: a public class must live in a file matching its name).
  • MyClassC - class MyClassC extends Object { } compiles. Every Java class implicitly extends Object, and making that explicit is redundant but not a compile error.
  • MyClassD - Compiles. Having a main method 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

#access modifiers#class declarations#public/default access#file structure

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice