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!
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.
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.
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.
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.
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".)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With