AP Computer Science A · Unit 1: Using Objects & Methods
1.10 Class Methods and Static Keyword
Static methods belong to the class
A static method (also called a class method) is marked with the `static` keyword and belongs to the class itself, not to any particular object. It can be called using the class name, like `Math.sqrt(25)`, without ever creating an instance of that class.
Static vs. instance methods
Instance methods operate on the data of a specific object and are called through an object reference. Static methods cannot access instance variables directly because there's no object involved — they only work with static (class) variables or their own parameters and local variables.
Common static examples
Utility classes like `Math` are full of static methods: `Math.pow()`, `Math.abs()`, `Math.random()`. Since these methods don't depend on object state, calling `new Math()` isn't needed — you simply write `Math.methodName(args)` directly using the class name.
Key terms
- Static method
- A method belonging to the class itself, marked with 'static', called using the class name without creating an object.
- Instance method
- A method that operates on a specific object's data; must be called through an object reference.
- Why can't static methods use instance variables?
- Because instance variables belong to individual objects, and static methods have no associated object.
- Example of calling a static method
- Math.sqrt(25) — called directly on the class name 'Math', no object needed.
- Static variable
- A variable shared by all instances of a class, accessible by static methods since it's not tied to any one object.
Try an AP-style question
How is a static method usually called?
- With the class name, like Math.sqrt(9)
- Only on a newly created object
- Using the keyword this in front
- It can't be called from anywhere
Show the answer
A. Belongs to the class.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 1.10 free in APrep