nerdexam
Oracle

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()…

Object-Oriented Programming Principles

Question

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 ("All the best"); m.readMsg(); Which code fragment can be inserted at line n1 to enable the code to print All the best?

Options

  • Avoid writeMsg();
  • BMessenger.writeMsg();
  • CwriteMsg();
  • Dm.writeMsg();

How the community answered

(30 responses)
  • A
    13% (4)
  • B
    77% (23)
  • C
    7% (2)
  • D
    3% (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 for static methods. Since writeMsg() is not static, this causes a compile error.
  • D (m.writeMsg()) references the variable m, which is declared outside the class in the outer scope - it is not in scope inside readMsg(), 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

#method invocation#instance methods#scope resolution#this reference

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice