nerdexam
Oracle

1Z0-803 · Question #73

Which three lines are illegal? 1. class StaticMethods { 2. static void one() { 3. two(); 4. StaticMethods.two(); 5. three(); 6. StaticMethods.four(); 7. } 8. static void two() { } 9. void three() { 10

The correct answer is C. line 5 D. line 6 H. line 13. Static methods cannot directly invoke non-static (instance) methods without an object instance, and non-static methods cannot be called using static class-level invocation syntax.

Working with Methods and Encapsulation

Question

Which three lines are illegal? 1. class StaticMethods { 2. static void one() { 3. two(); 4. StaticMethods.two(); 5. three(); 6. StaticMethods.four(); 7. } 8. static void two() { } 9. void three() { 10. one(); 11. StaticMethods.two(); 12. four(); 13. StaticMethods.four(); 14. } 15. void four() { } 16. }

Options

  • Aline 3
  • Bline 4
  • Cline 5
  • Dline 6
  • Eline 10
  • Fline 11
  • Gline 12
  • Hline 13

How the community answered

(21 responses)
  • A
    5% (1)
  • C
    86% (18)
  • G
    10% (2)

Why each option

Static methods cannot directly invoke non-static (instance) methods without an object instance, and non-static methods cannot be called using static class-level invocation syntax.

Aline 3

Calling the static method `two()` directly from another static method `one()` is legal in Java.

Bline 4

Calling the static method `two()` using the class name `StaticMethods.two()` from a static method `one()` is legal in Java.

Cline 5Correct

Calling the non-static method `three()` from the static method `one()` is illegal because static methods operate at the class level and do not have access to instance-specific members without an explicit object instance.

Dline 6Correct

Calling the non-static method `four()` using the class name `StaticMethods.four()` from a static method is illegal because `four()` is an instance method, requiring an object instance for invocation, even when specifying the class.

Eline 10

Calling the static method `one()` directly from a non-static method `three()` is legal, as non-static methods can access static members.

Fline 11

Calling the static method `two()` using the class name `StaticMethods.two()` from a non-static method `three()` is legal.

Gline 12

Calling the non-static method `four()` directly from another non-static method `three()` within the same class is legal.

Hline 13Correct

Attempting to call the non-static method `four()` using `StaticMethods.four()` from a non-static context is illegal because it incorrectly tries to invoke an instance method in a static manner, which is only valid for static methods.

Concept tested: Java static and instance method invocation rules

Source: https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

Topics

#static methods#instance methods#method invocation#compilation error

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice