Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a class named Media which has a method named setLoanItem:

public void setLoanItem(String loan) {     this.onloan = loan; } 

I am trying to call this method from a class named GUI in the following way:

public void loanItem() {     Media.setLoanItem("Yes"); } 

But I am getting the error

non-static method setLoanItem(java.lang.String) cannot be referenced from a static context

I am simply trying to change the variable onloan in the Media class to "Yes" from the GUI class.

I have looked at other topics with the same error message but nothing is clicking!

like image 544
Daniel Mckay Avatar asked Feb 07 '11 14:02

Daniel Mckay


People also ask

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

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.

What does it mean non-static method Cannot be referenced from a static context?

A non-static method is dependent on the object. It is recognized by the program once the object is created. But a static method can be called before the object creation. Hence you cannot make the reference.

Can't be referenced from a static context?

And if no class instance is created, the non-static variable is never initialized and there is no value to reference. For the same reasons, a non-static method cannot be referenced from a static context, either, as the compiler cannot tell which particular object the non-static member belongs to.

Why non-static variable Cannot be referenced from a static context?

This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.


1 Answers

Instance methods need to be called from an instance. Your setLoanItem method is an instance method (it doesn't have the modifier static), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this)).

You need to create an instance of the class before you can call the method on it:

Media media = new Media(); media.setLoanItem("Yes"); 

(Btw it would be better to use a boolean instead of a string containing "Yes".)

like image 82
Nathan Hughes Avatar answered Sep 25 '22 04:09

Nathan Hughes