简体   繁体   中英

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

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

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.

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:

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

You need to correctly 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 so via 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 that instance around.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM