Bird
0
0

How can you modify this class to allow creating objects with either no parameters or with parameters?

hard📝 Application Q9 of 15
Java - Constructors

How can you modify this class to allow creating objects with either no parameters or with parameters?

class Animal {
  String type;
  int legs;
  Animal(String t, int l) {
    type = t;
    legs = l;
  }
}
AAdd a default constructor with no parameters initializing fields
BRemove the parameterized constructor
CMake the parameterized constructor private
DUse static methods instead of constructors
Step-by-Step Solution
Solution:
  1. Step 1: Understand constructor overloading

    Java allows multiple constructors with different parameter lists.
  2. Step 2: Add default constructor

    Adding a no-parameter constructor lets objects be created without arguments.
  3. Final Answer:

    Add a default constructor with no parameters initializing fields -> Option A
  4. Quick Check:

    Overload constructors for flexibility [OK]
Quick Trick: Add no-arg constructor to allow empty object creation [OK]
Common Mistakes:
  • Removing useful constructors
  • Making constructors private unnecessarily
  • Confusing static methods with constructors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes