Sobes.tech
Junior — Middle

Can you give examples of different types of constructors in object-oriented programming?

sobes.tech AI

Answer from AI

In object-oriented programming (OOP), there are different types of constructors that help create objects with various initial states:

  • Default constructor — takes no parameters and initializes the object with default values.
  • Parameterized constructor — takes parameters to initialize the object with specific values.
  • Copy constructor — creates a new object as a copy of an existing one.
  • Factory constructor (e.g., in Dart/Flutter) — returns an instance of the class, which can be a new object or an existing one.

Example in Dart (Flutter):

class User {
  String name;
  int age;

  // Default constructor
  User() {
    name = 'Guest';
    age = 0;
  }

  // Parameterized constructor
  User.withDetails(this.name, this.age);

  // Factory constructor
  factory User.guest() {
    return User();
  }
}

void main() {
  var user1 = User(); // default
  var user2 = User.withDetails('Alice', 30); // with parameters
  var user3 = User.guest(); // factory
}