Bird
0
0

You are designing a Java class Smartphone that must always have a brand and model specified when an object is created. Which constructor approach is best?

hard📝 Application Q8 of 15
Java - Constructors
You are designing a Java class Smartphone that must always have a brand and model specified when an object is created. Which constructor approach is best?
AAvoid constructors and initialize brand and model directly in the class
BUse only a default constructor that sets brand and model to empty strings
CCreate multiple constructors with no parameters and set brand/model later via methods
DDefine a constructor with parameters for brand and model, and no default constructor
Step-by-Step Solution
Solution:
  1. Step 1: Understand requirement

    The class must ensure brand and model are always set when creating an object.
  2. Step 2: Evaluate constructor options

    A parameterized constructor enforces setting these values at creation time.
  3. Step 3: Why other options fail

    Default constructors or setting values later can lead to uninitialized or invalid objects.
  4. Final Answer:

    Define a constructor with parameters for brand and model, and no default constructor -> Option D
  5. Quick Check:

    Parameterized constructor enforces required fields [OK]
Quick Trick: Use parameterized constructor to enforce required fields [OK]
Common Mistakes:
  • Using default constructor without parameters
  • Setting fields after object creation
  • Initializing fields directly without constructor

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes