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!
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".)