LearnFrenzy
Sign in Take a free test

Constructors and the this Keyword · Find the Error · Question 7

Error: returning a value from a constructor Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
class Fan {
    int speed;
    Fan(int speed) {
        this.speed = speed;
        return this;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(new Fan(3).speed);
    }
}
  • A speed must be private
  • B A constructor has no return type, so it cannot return a value (only a bare return; is allowed) Correct
  • C this cannot be returned anywhere
  • D Fan needs a no-arg constructor
Correct Answer: Option B

new already gives back the object.

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