LearnFrenzy
Sign in Take a free test

Classes and Objects · Predict the Output · Question 19

A parameter with the same name as a field Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 19 Back to Exercise

What is the output of the following Java program?

Main.java
class Car {
    String model = "unknown";
    void setWrong(String model) { model = model; }        // assigns the parameter to itself
    void setRight(String model) { this.model = model; }   // this.model is the field
}

public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        c.setWrong("Nexon");
        System.out.print(c.model + " ");
        c.setRight("Creta");
        System.out.println(c.model);
    }
}
  • A unknown Creta Correct
  • B Nexon Creta
  • C unknown unknown
  • D Compilation error
Correct Answer: Option A

Inside setWrong, model means the parameter, so the field never changes. this.model refers to the field.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links