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!
setLoanItem is an instance method, meaning you need an instance of the Media class in order to call it. You're attempting to call it on the Media type itself.
You may want to look into some basic object-oriented tutorials to see how static/instance members work.
Instance methods need to be called from an instance. Your
setLoanItem
method is an instance method (it doesn't have the modifierstatic
), 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:
(Btw it would be better to use a boolean instead of a string containing "Yes".)
You need to correctly separate static data from instance data. In your code,
onLoan
andsetLoanItem()
are instance members. If you want to reference/call them you must do so via an instance. So you either wantor
depending on how you want to pass that instance around.
setLoanItem()
isn't a static method, it's an instance method, which means it belongs to a particular instance of that class rather than that class itself.Essentially, you haven't specified what media object you want to call the method on, you've only specified the class name. There could be thousands of media objects and the compiler has no way of knowing what one you meant, so it generates an error accordingly.
You probably want to pass in a media object on which to call the method: