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.
Question
Options
- Aline 3
- Bline 4
- Cline 5
- Dline 6
- Eline 10
- Fline 11
- Gline 12
- Hline 13
How the community answered
(21 responses)- A5% (1)
- C86% (18)
- G10% (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.
Calling the static method `two()` directly from another static method `one()` is legal in Java.
Calling the static method `two()` using the class name `StaticMethods.two()` from a static method `one()` is legal in Java.
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.
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.
Calling the static method `one()` directly from a non-static method `three()` is legal, as non-static methods can access static members.
Calling the static method `two()` using the class name `StaticMethods.two()` from a non-static method `three()` is legal.
Calling the non-static method `four()` directly from another non-static method `three()` within the same class is legal.
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
Community Discussion
No community discussion yet for this question.