简体   繁体   中英

How to avoid the “non-static method referenced from a static context” in java ? really simple

When I tried to build this program there's always a error like " non-static method referenced from a static context " I think that because I can use "addto" function in "main". So how can I solve this problem? I need a public arraylist because I have to do the calculations in "addto"

Thx!

public class Calculation {  
    ArrayList<int[]> cal = new ArrayList<>();

    public static void main(String[] args) {
    System.out.println(addto(3,5));
    }

    String addto(int figone, int figtwo){
     ........do the calculations by using arraylist cal
    }
 }

You need to instantiate a Calculation object inside the main function in order to use Calculation's non-static methods.

Non-static methods only "exist" as members of an object (which you can think of as instances of classes). In order to make this work you'd need to write:

System.out.println(new Calculation().addto(3, 5))

Really simple?

System.out.println(new Calculation().addto(3,5));

or

Calculation calculation = new Calculation();
System.out.println(calculation.addto(3,5));
// and use 'calculation' some more ...

(You could also add a static modifier to the addto method declaration, but you would then need to make cal static too so the addto can use it. Bad idea.)


OK. So what the compilation method is actually saying is that addto is declared as an instance method ... but you are trying to call it without saying which instance to use. In fact, you are trying to call it as if it was a static method.

The "fix" (see above) is to create an instance and call the method on that.

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