dev only

Creating & Initializing Objects: Constructors

Building an Object with new

A constructor initializes a new object's attributes when it's created. To build one, use new followed by the class name — that's actually a call to the constructor:

TalonFX leftMotor = new TalonFX(5); // 5 is the CAN ID — argument order matters

Constructors Can Be Overloaded

A class can offer more than one constructor — different ways to set up an object, distinguished by their parameter lists. This is the same overloading concept from methods (Lesson 4.1), applied to constructors:

Pose2d start1 = new Pose2d();                       // no-argument constructor: defaults to (0, 0, facing 0°)
Pose2d start2 = new Pose2d(1.0, 2.0, new Rotation2d()); // x, y, and heading, explicitly

Argument order matters — mixing up which number means what (is it x-then-y, or y-then-x?) produces a real, silent bug: the code compiles fine, but the object ends up with the wrong values.

Object References and null

A reference variable can be declared without pointing at any object yet — that's null, meaning "doesn't refer to anything."

TalonFX intakeMotor = null; // no object yet
intakeMotor = new TalonFX(7); // now it does

Calling a method on a null reference — one that was declared but never actually constructed — throws a NullPointerException at runtime (more on this in the next lesson).

Constructor Signatures

Just like methods, a constructor has a signature: its name (always the same as the class) plus its parameter types. Look up a library class's constructors in its documentation to see what arguments it expects and in what order.

public class Pose2d {
    public Pose2d() { /* implementation not shown */ }
    public Pose2d(double x, double y, Rotation2d rotation) { /* implementation not shown */ }
}

Common Pitfalls

  • Forgetting new. TalonFX leftMotor = TalonFX(5); doesn't compile — creating an object always requires new.
  • Mixing up argument order. A constructor taking (x, y, rotation) called as (rotation, x, y) either won't compile (wrong types) or, worse, compiles with the wrong values silently swapped.
  • Calling a method on an unconstructed reference. Declaring TalonFX m; without ever assigning new TalonFX(...) to it leaves m as null — calling m.set(0.5) crashes with a NullPointerException.

Key Takeaways

  • new ClassName(arguments) calls a constructor to build and initialize an object.
  • A class can have multiple overloaded constructors, differing in their parameter lists.
  • A reference variable can be null — pointing at no object at all — until it's assigned a real one with new.
  • Calling a method on a null reference throws a NullPointerException.
  • Constructor argument order must match the constructor's signature exactly.

Derived from csawesome-2026: unit-1-using-objects-and-methods/1.13-creating-and-initializing-objects-constructors.md (CSA 1.13)