Unit 3 Cycle 2 Day 5: Static vs Instance Method Error

Unit 3 Advanced (Cycle 2) Day 5 of 28 Advanced

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.

public class Account { private double balance; private static double rate = 0.05; public Account(double b) { balance = b; } public static double getRate() { return rate; } public static double getBalance() { return balance; } }

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.

Review this topic: Section 3.8 — Static Methods • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.