0

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
    }
 }
1
  • 1
    you need an instance of Calculation in order to invoke the non-static method addto Commented Nov 19, 2012 at 3:44

2 Answers 2

4

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))
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Yes: System.out.println(new Calculation().addto(3,5));. No: or add a static modifier to the addto method declaration. Not unless you also make "cal" static. Your first suggestion was best :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.