2

I've asked my teacher this a thousand times and he explained it to me just as many times, but I still don't get when to use static in variables/methods

Could someone give a metaphorical explanation for this, maybe also showing some examples where static is needed and where not?

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
Boyen
  • 1,429
  • 2
  • 15
  • 22
  • 1
    Long ago I wrote about different kinds of *variables* in Java, including static fields and instance fields. See if this helps you: http://stackoverflow.com/questions/8005250/difference-between-a-static-and-a-final-static-variable-in-java/8005268#8005268 – Bruno Reis Apr 05 '13 at 07:11
  • possible duplicate of [Java: when to use static methods](http://stackoverflow.com/questions/2671496/java-when-to-use-static-methods) – Andreas Fester Apr 05 '13 at 07:12
  • http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html – JB Nizet Apr 05 '13 at 07:12
  • 2
    If even your teacher has explained to you *a thousand times* then why do you think that some random people here at SO would be better at explaining? That's what teachers are for. Ask your teacher again. Let him/her explain again with *metaphorical or really clear explanation*. – maba Apr 05 '13 at 07:12
  • See also http://stackoverflow.com/questions/538870/java-static-methods-best-practices?rq=1 – Andreas Fester Apr 05 '13 at 07:13
  • @maba: Hmm, I hope that an explanation coming from someone else could maybe cover the one thing he's missing, or doesn't explain correclt, maybe someone here has a metaphore for this that he didn't think of, I hope so atleast – Boyen Apr 05 '13 at 07:15
  • How about your classmates? Have some local discussions and you will all learn from each other. – maba Apr 05 '13 at 07:17
  • The problem there is that the static subject isn't handled in class yet, it's left aside untill other basic subjects are covered ( first year in java), personally I study alot for java at home, as I already require it for practical usages, now I haven't really stumbled with problems on static yet( I don't put static unless I get an error in compiling), I'd like to know what it's for – Boyen Apr 05 '13 at 07:20

4 Answers4

1

Do I want to access the method without an instance of the class?

If you answered yes, you probably want a static method.

private static variables can be used to share data across instances of that class, i.e. if you have:

public class Car
{
    private static int wheelsNum;
    private String company;
    private String color;
    ...
    ...
}

Then if you change wheelNum to be 2, then all cars will have 2 wheels.

For example, consider this piece of code:

Car car1 = new Car();
Car car2 = new Car();

car1.setColor("Yellow");
car2.setColor("Blue");

car1.setWheelsNum(4);
car2.setWheelsNum(2);

Then both cars will have 2 wheels, although I "didn't" mean to change the wheels number of the first car. But, as you can tell, the cars have different colors.

public static variables used without making instance of the class, wheras private static variables are not.

When you need to use a variable in a static function, you can only use static variables, so making it private to not access them from other classes.

Static methods can't access non-static methods (and the same for variables).

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • If I would change wheelsNum to non-static here, why wouldn't all the cars have 2 wheels then? – Boyen Apr 05 '13 at 07:28
  • Say you have two instances of the class, then you can have a color, and I can have a different color. If you change your car's color, my car still with the same color. But if you change the static field(wheelsNum) then all the cars will have 2 wheels (which could lead to a disaster :) ) – Maroun Apr 05 '13 at 07:32
  • You said "Static methods can't access non-static methods (and the same for variables)." How about static methods accessing non-static variables? – Boyen Apr 05 '13 at 07:50
  • You can't access stativ variable from non-static method. And that's make a lot of sense.. Think about it and you'll know why :) – Maroun Apr 05 '13 at 08:00
  • I tried to think about it but it doesnt seem to fit in my mind, Lets say we have a method called changeWheelRackSize() , this method would not be static but it would still need to acces the value of WheelsNum , right? – Boyen Apr 05 '13 at 08:14
1

I'm gonna try to explain as short and simple as possible, I am a student too. A static variable or method, DOES NOT CHANGE with every instance. Example, we have this test class:

        Class Test(){
         String name;
         static int money;
         public test(String name, int money){
           this.name = name;
           this.money = money;
         }
    //Changes money value
         public void setMoney(int money){
          this.money = money;
    }
   public int getMoney(){
    return this.money 
}
        }

Now we are gonna create 2 test instances of test(): Test test1 = new test("test1", 10); Here, the name of the instance of test1 is "test1" and the money value is 10. Test test2 = new test("test2", 20); Now, the name of the instance of test1 is still "test1", but the money value is now 20! This can be useful when you need for example counting how many instances have created, or in general counting. It is really powerful, with a static variable you can just simply change the attributes of avery instance. If I now do test1.setMoney(1000), test1.getMoney vill return 1000 and test2.getMoney will return 1000 too I hope I could help...

Fabiotocchi
  • 226
  • 3
  • 11
  • I'm sorry for the bad formatting, i am new on stackoverflow, i nedd to get hand with it, sorry – Fabiotocchi Apr 05 '13 at 07:27
  • Then why not using a variable initialised in the first class and accessed by others ? – Boyen Apr 05 '13 at 07:38
  • Well, when you have big programms with a lot of classes and subclasses, it get annoying and difficult to change every time: example for your method every time you want to do like money++ when you create another test class with the constructor, to add +1 to the money, you nedd to do: test1.setMoney(test1.getMoney++); and then the total money value will be stored in test1.getMoney(), making all the other getMoney instances, like test2.getMoney() useless cause they don't have the total value. With a static variable, avery time you call the contructor you just need to add a this.money++ inside – Fabiotocchi Apr 05 '13 at 07:54
  • It's hard to explain, but has I said, you're gonna need this when you're gonna create big, managing applications – Fabiotocchi Apr 05 '13 at 07:55
0

You asked for examples, here's a simple one:

The Integer class has an intValue() method. It only makes sense for an instance of this class, so this method cannot be static.

This class also has a valueOf() method, that returns an instance of the class from the specified int. You don't need to have an existing instance to call this method, so this method is static.

WilQu
  • 7,131
  • 6
  • 30
  • 38
0

I finally understand, thanks to Maroun Maroun!

For other people reading this question , I figured out a clear way to explain this matter (correct me if I'm wrong though!)

Let's say we have a class named Person.

every instance of this class creates a new person with the variables that define him, so the variable "age" and "name" are assigned to this person, therefore non-static,

every instance of this class also adds 1 to the amount of persons in total, therefore this variable value is shared amongst all the persons, this variable must be static.

public class Person {


    private static int amountOfPersons;
    private String name;
    private int age;

    public static void main(String[] args) {
        Person person1 = new Person();
        Person person2 = new Person();
        person1.age = 10;
        person2.age = 20;
        person1.name="Johnny";
        person2.name="Brian";
        System.out.println(person1.amountOfPersons+" "+person1.name+" "+person1.age);
        System.out.println(person2.amountOfPersons+" "+person2.name+" "+person2.age);
    }
    public Person(){
        Person.amountOfPersons++;
    }
} 
Boyen
  • 1,429
  • 2
  • 15
  • 22