0

So I seem to be struggling a little bit with static in general. What exactly does static do in Java and how do you fix it? For example, here is a bit of code

public class StaticProblem
{
    static int number;
    static int valOne, valTwo, valThree;

    public static void main(String args)
    {
        // stuff

        valOne = method1(number);
        valThree = method2(val1, val2);
    }

    public static int method1(int parameter)
    {
        int var;
        // stuff
        return parameter + var;
    }

    public static int method2(int parm1, int parm2) 
    {
        int othervar;
        // more stuff

        return parm1 + parm2 + othervar;
    }

    :
}

How exactly would one go about fixing the "static" problem so that static is no longer used. I sort of understand that static in Java allows the value of one object to be shared with new objects that are created (for example, 15 cards all share the same gas left in the tank - if one car goes empty, then the rest go empty as well). I thought I knew how to fix this code and I assumed it involved making a new StaticProblem object in the main method. However, I am a bit lost.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • where is `val1` declared? – Bohemian May 10 '16 at 21:14
  • sorry meant for it to be "valOne." - fixed – Baconlord99 May 10 '16 at 21:15
  • Did you try making a new "StaticProblem" object in the main method? What happened when you did? – Rabbit Guy May 10 '16 at 21:16
  • Yeah, that's the thing. I tried, but I couldn't remember how that code is suppose to look. I'm a bit of a novice at coding and this was an example someone provided to me so I'm just trying to understand how this should look without static. I do know that you are supposed to make new objects each time or something like that, but I'm not sure how the syntax looks. I apologize if this looks like a duplicate, but I was little unsure. – Baconlord99 May 10 '16 at 21:19
  • Show us the code where you tried to create the StaticProblem object in the main method, please. It sounds like your real issue is not understanding how to do that. – Rabbit Guy May 10 '16 at 21:20

1 Answers1

0

Your methods need to be static in order to be called since there is no object (class instance) to call the methods on. You could change that by writing something like the following:

public class Program {
    public static void main(String[] args) {
        new Program.run(); //this creates an object so you can get rid of static methods
    }

    void run() {
        //your code goes here instead of inside main
        ...
    }

    void method1() { //these no longer have to be static
        ...
    }

    void method2() {
        ...
    }
}
RaminS
  • 2,208
  • 4
  • 22
  • 30