Unit 3 Cycle 2 Day 5: Static vs Instance Method Error
Share
Static vs Instance Method Error
Section 3.8 — Static Methods
Key Concept
A static method cannot call an instance method or access an instance variable without an object reference. The error non-static variable cannot be referenced from a static context occurs when static code tries to use this or instance members directly. The fix is either making the method non-static, passing an object as a parameter, or creating an object within the static method. The AP exam presents code in the main method (which is static) that incorrectly tries to call instance methods without creating an object first.
Consider the following class.
Which method causes a compile-time error?
Answer: (B) getBalance()
getBalance() is static but tries to access balance, which is an instance variable. Static methods cannot access instance variables because there is no object context.
Why Not the Others?
(A) getRate() is static and accesses the static variable rate. This is valid.
(C) Only getBalance() has the error. getRate() correctly accesses a static variable.
(D) getBalance() is incorrectly declared as static while accessing an instance variable.
Common Mistake
Static methods can only access static variables. Instance variables belong to objects, and static methods have no this reference to an object.
AP Exam Tip
Static methods: can access static variables and other static methods. Cannot access instance variables or instance methods. This rule is absolute.