Bird
0
0

Consider this class:

hard📝 Application Q9 of 15
Java - Constructors

Consider this class:

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

What will new Rectangle(5) create?

AA rectangle with width 5 and height 1
BA rectangle with width 1 and height 5
CA square with width and height 5
DCompilation error due to ambiguous constructor
Step-by-Step Solution
Solution:
  1. Step 1: Match constructor call to signature

    new Rectangle(5) matches constructor with one int parameter.
  2. Step 2: Understand constructor behavior

    That constructor sets width and height both to 5, creating a square.
  3. Final Answer:

    A square with width and height 5 -> Option C
  4. Quick Check:

    Single-parameter constructor sets both dimensions equal [OK]
Quick Trick: Single int parameter sets width and height equally [OK]
Common Mistakes:
  • Assuming default height 1 is used
  • Confusing which constructor is called
  • Expecting compilation error

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes