dev only

Calling Instance Methods

Instance Methods vs. Static Methods

Lesson 4.2 covered static (class) methods, called via the class name. An instance method is the opposite: it's always called on a specific object, and it reads or changes that object's attributes.

leftMotor.set(0.5); // instance method — acts on leftMotor specifically, not TalonFX in general

Math.sqrt(9) doesn't care which object called it (there is no object) — it's pure computation. leftMotor.set(0.5) only makes sense applied to one specific motor.

NullPointerException

Calling a method on a reference that's null — declared but never actually built with new — throws a NullPointerException at runtime. This is one of the most common real bugs in object-oriented code:

TalonFX intakeMotor = null;
intakeMotor.set(0.5); // crashes: intakeMotor doesn't refer to a real object yet

Methods With Arguments

Just like the constructors from the last lesson, instance methods can take arguments:

leftMotor.set(0.5);          // no extra behavior beyond the speed itself
elevator.moveToPosition(24.0); // 24.0 is the argument, saved into the method's parameter

Getters (Accessors)

A method that just reports one of an object's attributes — no side effects, just returns a value — is a getter (formally, an accessor). By convention its name starts with get, and its return value must actually be used:

double speed = leftMotor.getVelocity(); // a getter — must use the returned value
System.out.println("Current speed: " + leftMotor.getVelocity());

Common Pitfalls

  • Calling an instance method without an object. TalonFX.set(0.5) doesn't make sense — set needs a specific motor to act on; only leftMotor.set(0.5) does.
  • Calling a method on a null reference. The single most common source of NullPointerException — make sure every object is actually constructed with new before calling anything on it.
  • Ignoring a getter's return value. leftMotor.getVelocity(); alone does nothing useful — a getter exists specifically to report a value you then use.

Key Takeaways

  • An instance method is called on a specific object and can read/change that object's own attributes; a static method belongs to the class itself.
  • Calling a method on a null reference throws a NullPointerException — one of the most common real bugs.
  • A getter (accessor) reports one of an object's attributes; its return value must be used, not ignored.

Derived from csawesome-2026: unit-1-using-objects-and-methods/1.14-calling-instance-methods.md (CSA 1.14)