nerdexam
Oracle

1Z0-803 · Question #259

Given: class Base { public static void main(String[] args) { System.out.println("Base " + args[2]); } } public class Sub extends Base{ public static void main(String[] args) { System.out.println("Over

The correct answer is B. Overridden 20. When executing a Java program via java ClassName, the JVM directly calls the main method of the specified ClassName. Static methods, including main, cannot be overridden in the same way instance methods are.

Working with Inheritance

Question

Given:

class Base { public static void main(String[] args) { System.out.println("Base " + args[2]); } } public class Sub extends Base{ public static void main(String[] args) { System.out.println("Overriden " + args[1]); } } And the commands:

javac Sub.java java Sub 10 20 30 What is the result?

Options

  • ABase 30
  • BOverridden 20
  • COverridden 20
  • DBase 30

How the community answered

(27 responses)
  • A
    19% (5)
  • B
    70% (19)
  • C
    4% (1)
  • D
    7% (2)

Why each option

When executing a Java program via `java ClassName`, the JVM directly calls the `main` method of the specified `ClassName`. Static methods, including `main`, cannot be overridden in the same way instance methods are.

ABase 30

Incorrect, `Base.main` is not executed because `java Sub` explicitly targets `Sub.main`.

BOverridden 20Correct

B is correct because the `java Sub` command directly invokes the `main` method defined in the `Sub` class, not the `main` method of its `Base` class. The arguments "10", "20", "30" are passed to `Sub.main`, and `args[1]` refers to "20", resulting in the output "Overridden 20".

COverridden 20

Incorrect, this choice is identical to the correct answer and represents the correct output.

DBase 30

Incorrect, `Base.main` is not executed because `java Sub` explicitly targets `Sub.main`.

Concept tested: Java program execution, static method overriding, command-line arguments.

Source: https://docs.oracle.com/javase/specs/jls/se17/html/jls-8.html#jls-8.4.8.2

Topics

#static methods#method hiding#command-line arguments#JVM execution

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice