Unit 3 Cycle 1 Day 8: Static Methods
Share
Static Methods
Section 3.8 — Static Methods
Key Concept
Static methods belong to the class and can be called without creating an object: ClassName.methodName(). They cannot access instance variables or call instance methods directly because there is no this reference. Static methods can only work with their parameters, local variables, and other static members. The main method is static, which is why it cannot directly call instance methods without first creating an object. The AP exam tests whether a method call from a static context is valid.
Consider the following class.
What does MathHelper.sumOfSquares(3, 4) return?
Answer: (B) 25
square(3)=9, square(4)=16. sumOfSquares=9+16=25.
Why Not the Others?
(A) 7 = 3+4, the sum without squaring.
(C) 49 = 7*7, as if the sum were squared instead of summing the squares.
(D) 12 = 3*4, the product of the arguments.
Common Mistake
Static methods are called on the class, not on objects: ClassName.method(). They cannot access instance variables because there is no object context.
AP Exam Tip
Static methods like Math.abs() and Math.sqrt() are called on the class name. They can only access other static members, not instance variables.