Constructor

A constructor is a special method that runs automatically when an object is created from a class. Its job is to set up the object’s initial state.

  new Player("Alice")
  ┌─────────────────────┐
  │     constructor     │  ← runs automatically
  │  sets name = Alice  │
  └─────────────────────┘
  Player object ready

What a Constructor Does#

When you create an object, you often need to give it some starting values — a name, a score, a position. The constructor receives those values as arguments and stores them on the object.

Without a constructor, you’d have to set every value manually after creating the object. The constructor lets you do it all in one step.

Common Mistakes#

Confusing the constructor with a regular method A constructor is not called by name — it runs automatically when you use new (or the equivalent). You never call a constructor directly after the object exists.

Forgetting to store arguments on the object Receiving a parameter in the constructor doesn’t automatically attach it to the object. You have to explicitly store it — the syntax for this varies by language, but the mistake is universal: the parameter arrives and then disappears because it was never saved.

Trying to return a value from a constructor Constructors don’t return values. Their only job is to set up the object. Attempting to return something is either ignored or a compile error depending on the language.

Resources#