1Z0-811 · Question #5
Given: class Messenger { String msg; Messenger(String msg) {this.msg = msg;} public void writeMsg() { System.out.println(msg); } public void readMsg () { // line n1 } } Messenger m = new Messenger…
The correct answer is B. Messenger.writeMsg(). There's an error in the listed answer - C is actually correct, not B. Here's the explanation: Option C (writeMsg();) is correct because readMsg() is an instance method inside the same Messenger class, so it can call writeMsg() directly - this is shorthand for this.writeMsg()…
Question
Options
- Avoid writeMsg();
- BMessenger.writeMsg();
- CwriteMsg();
- Dm.writeMsg();
How the community answered
(30 responses)- A13% (4)
- B77% (23)
- C7% (2)
- D3% (1)
Explanation
There's an error in the listed answer - C is actually correct, not B. Here's the explanation:
Option C (writeMsg();) is correct because readMsg() is an instance method inside the same Messenger class, so it can call writeMsg() directly - this is shorthand for this.writeMsg(), which is always valid within the same class instance.
Why the others are wrong:
- A (
void writeMsg();) is a method declaration stub, not a method call - it's a syntax error in this context. - B (
Messenger.writeMsg()) attempts to call an instance method using the class name, which is only valid forstaticmethods. SincewriteMsg()is not static, this causes a compile error. - D (
m.writeMsg()) references the variablem, which is declared outside the class in the outer scope - it is not in scope insidereadMsg(), causing a compile error.
Memory tip: When calling an instance method from within the same class, you never need a reference - just use the method name directly (the compiler implicitly uses this). Only use ClassName.method() for static methods.
Note: The answer key you were given lists B as correct, but that is a mistake. B would fail to compile. Flag this with your instructor.
Topics
Community Discussion
No community discussion yet for this question.