"A non-static method cannot refer to a static context"

I have a class called Media that has a method called setLoanItem :

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

I am trying to call this method from a class named GUI as follows:

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

But I get an error

non-static setLoanItem method (java.lang.String) cannot reference a static context

I'm just trying to change the onloan variable in the Media class to "Yes" from the GUI class.

I looked at other topics with the same error message, but nothing clicks!

+60
java static compiler-errors
Feb 07 2018-11-14T00:
source share
4 answers

Instance methods must be called from an instance. Your setLoanItem method is an instance method (it does not have a static modifier) โ€‹โ€‹that must be in order to function (because it sets the value for the instance it called ( this ) on)). You need to instantiate the class before you can call the method on it:

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

(Btw would be better off using a boolean instead of a string containing "Yes.")

+70
Feb 07 2018-11-14T00:
source share

setLoanItem is an instance method, that is, you need an instance of the Media class to call it. You are trying to call it by the type of Media itself.

You might want to check out some basic object-oriented tutorials to find out how static / instance members work.

+11
Feb 07 2018-11-14T00:
source share

setLoanItem() not a static method, it is an instance method, which means that it belongs to a specific instance of this class, and not to the class itself.

In fact, you did not indicate which media object you want to call the method on, you specified only the class name. There may be thousands of media objects, and the compiler does not know what you had in mind, so it generates an error accordingly.

You probably want to pass the media object to which the method is called:

 public void loanItem(Media m) { m.setLoanItem("Yes"); } 
+2
Feb 07 2018-11-11T00:
source share

You need to properly separate static data from instance data. In your code, onLoan and setLoanItem() are instance members. If you want to reference / call them, you must do this through an instance. So you either want

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

or

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

depending on how you want to pass this instance.

0
Feb 07 2018-11-14T00:
source share



All Articles