A Non-static method cannot be referenced from a static context error

667    Asked by Ankesh Kumar in Python , Asked on Jul 14, 2021

Getting an error when inserting String value from R.string resource XML file:

public static final String TT =  (String) getText(R.string.TT);

This is the error message:

Error: Cannot make a static reference to the non-static method getText(int) from the type Context

How do you fix non-static method Cannot be referenced from a static context Java?

Answered by Carolyn Buckland

There is one simple way of solving the non-static variable cannot be referenced from a static context error. In the above code, we have to address the non-static variable with the object name. In a simple way, we have to create an object of the class to refer to a non-static variable from a static context.


Note: A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class.

Every method in java is a non-static method, but the methods must not have a static keyword before the method name. non-static methods can access any static method and static variable also, without using the object of the class.



Your Answer

Interviews

Parent Categories