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.

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

Math.sqrt(9) doesn't care which object called it (there is no object) — it's pure computation. leftMotor.setThrottle(0.5) only makes sense applied to one specific motor. (leftMotor is a DriveMotor, the team's own motor class from Lesson 4.4.)

NullPointerException

Calling a method on a reference that holds null — set to null and never assigned a real object with new — throws a NullPointerException at runtime. This is one of the most common real bugs in object-oriented code:

DriveMotor intakeMotor = null;
intakeMotor.setThrottle(0.5); // crashes: intakeMotor doesn't refer to a real object

Methods With Arguments

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

leftMotor.setThrottle(0.5);    // 0.5 is the argument: half throttle forward
elevator.moveToPosition(24.0); // 24.0 is the argument, saved into the method's parameter

(elevator is an object of another of the team's own classes, Elevator.)

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 should actually be used. getThrottle() reports the last throttle this motor was told to run at:

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

Common Pitfalls

  • Calling an instance method without an object. DriveMotor.setThrottle(0.5) doesn't compile — Java reports "non-static method setThrottle(double) cannot be referenced from a static context," because setThrottle needs a specific motor to act on. Only leftMotor.setThrottle(0.5) works.
  • 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.getThrottle(); 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 should be used, not ignored.

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