Cannot Make a Static Reference to The Non-static Method or Field

This post shows what does “Cannot make a static reference to the non-static method or a non-static field” error means and how to fix that error.

static reference to the non-static method or field

In order to understand why this error “Cannot make a static reference to the non-static method or a non-static field” crops up you’ll have to understand the difference between instance member (field and method) and class members.

Instance members– These members i.e. instance fields and instance methods belong to an instance (object) of a class. You can invoke instance methods and access instance variables only through an object of the class and each object of the class has its own separate copy of the instance members.

Class members (Static members)– Static members of the class are associated with the class which means separate copies of fields and methods declared as static won’t be created for every object of the class. You can access only static members from a static context.

So you see the problem here? You can access a static method with out even creating any object of the class but trying to access a non-static method from that static method poses the dilemma; to which instance does that non-static method belong to, any instance of the class is even created or not. That’s why you get this error “Cannot make a static reference to the non-static method or a non-static field”.

For example consider the following class where we are trying to invoke a non-static method instanceMethod() from the static main method and also trying to access non-static field i.

Code gives compile-time error for both of the non-static members.

Fixing static reference to the non-static method or field error

As you must be knowing by now you need an object to access instance members of the class so create an object and use that to access non-static fields.

Output

That’s all for the topic Cannot Make a Static Reference to The Non-static Method or Field. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.