APrep Open the app

AP Computer Science A · Unit 1: Using Objects & Methods

1.9 Using Objects

Objects hold state and behavior

An object is an instance of a class, created with the new keyword, which calls a constructor. Objects have instance variables (state/attributes) and methods (behavior). Using an object means calling its methods with dot notation, like `myCar.startEngine();`, to access or change its data.

Calling methods on objects

Methods are invoked using objectName.methodName(arguments). Non-static methods require an object reference because they act on that object's specific instance data. The return value of a method call can be stored in a variable, passed as an argument, or used directly in an expression — but only if types match.

Multiple objects, independent state

Each object created from a class has its own copy of instance variables. Changing one object's state (e.g., `dog1.setName("Rex")`) does not affect another object (`dog2`) of the same class. This independence is key to modeling real-world entities separately in code.

Key terms

Object
An instance of a class, created using 'new', with its own state and behavior.
Dot notation
Syntax used to call a method or access a variable on an object: objectName.methodName().
Constructor
A special method called when an object is created that initializes its instance variables.
Instance variable
A variable that belongs to a specific object, with each object having its own independent copy.
Independence of objects
Changing one object's state does not affect other objects of the same class, since each has separate instance variables.

Try an AP-style question

Code

String s = null;
int n = s.length();

What happens when this runs?

  1. n is set to −1
  2. A NullPointerException is thrown
  3. A compile error occurs
  4. n is set to 0
Show the answer

B. No object to call a method on.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 1.9 free in APrep