beginnerFree

Constructors

Initialize objects - same name as class, no return type

Constructors

Constructors run when you create an object. Use them to set initial state.

The narrated version of this skribble — tap play for the full-size video.

0:00 / 2:19

The Big Picture

Constructors initialize objects when you call new. They set initial state, validate inputs, and allocate resources.

  • Same name as the class, no return type
  • Can be overloaded with different parameters
  • Run once per object creation, before any other access

Every class has at least one (default or explicit).

How It Works

No explicit constructor? Java provides a no-arg default. Add any constructor and the default disappears.

  • Chain with this(...) to delegate within same class
  • super(...) explicitly calls a parent constructor; else Java inserts super()
  • Superclass constructor always runs first
  • Fields initialize before constructor body executes

In the Java Landscape

Java 16+ records auto-generate canonical constructors.

  • Builder pattern avoids telescoping constructors
  • Static factory methods (of(), create()) often replace them
  • DI frameworks (Spring) call constructors to wire beans
  • Lombok @AllArgsConstructor generates constructors
  • Copy constructors for defensive copying

Pitfalls and Best Practices

  • Validate parameters - fail fast with IllegalArgumentException
  • Don't call overridable methods in constructors
  • Consider static factories when named creation/validation/caching helps
  • Use this(...) chaining to avoid duplicate logic
  • Keep constructors simple - complex logic in factories
  • Document required vs optional parameters
#java#oop#constructors