Bird
0
0

Given the class below, how can you create a method that returns a new Rectangle object with double the width and height of the current one?

hard📝 Application Q15 of 15
Java - Object-Oriented Programming Concepts
Given the class below, how can you create a method that returns a new Rectangle object with double the width and height of the current one?
class Rectangle {
  int width;
  int height;

  Rectangle(int w, int h) {
    width = w;
    height = h;
  }

  // Your method here
}
ARectangle doubleSize() { return new Rectangle(width * 2, height * 2); }
Bvoid doubleSize() { width *= 2; height *= 2; }
CRectangle doubleSize() { width *= 2; height *= 2; return this; }
DRectangle doubleSize() { return new Rectangle(width + 2, height + 2); }
Step-by-Step Solution
Solution:
  1. Step 1: Understand the requirement

    The method should return a new Rectangle object with width and height doubled, without changing the current object.
  2. Step 2: Evaluate each option

    Rectangle doubleSize() { return new Rectangle(width * 2, height * 2); } creates and returns a new Rectangle with doubled dimensions. void doubleSize() { width *= 2; height *= 2; } changes current object and returns void. Rectangle doubleSize() { width *= 2; height *= 2; return this; } changes current object and returns it. Rectangle doubleSize() { return new Rectangle(width + 2, height + 2); } adds 2 instead of doubling.
  3. Final Answer:

    Rectangle doubleSize() { return new Rectangle(width * 2, height * 2); } -> Option A
  4. Quick Check:

    Return new object with doubled size = Rectangle doubleSize() { return new Rectangle(width * 2, height * 2); } [OK]
Quick Trick: Return new object; don't modify current one [OK]
Common Mistakes:
  • Modifying current object instead of returning new
  • Adding instead of multiplying dimensions
  • Returning void instead of new object

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes