-1

I'm just learning java and have come across two ways to do the same thing. My question is: what is the difference between them? Thanks.

Option A:

class Foo {
    public static int var;

    Foo (){
        var = 0;
    }

    public static void main(String[] args) {
        Foo object = new Foo();
        object.method();
        System.out.println(object.var); //prints 1
    }

    public void method (){
        var++;
    }
}

Option B:

class Foo {
    public static int var;

    Foo (){
        var = 0;
    }

    public static void main(String[] args) {
        Foo object = new Foo();
        method(object);
        System.out.println(object.var); //prints 1
    }

    public static void method (Foo object){
        object.var++;
    }
}
  • 1
    A is incrementing the `var` using an object's method the B is increment `var` using a static method that can be called without creating an object. – Rod_Algonquin Apr 29 '15 at 01:07
  • Why pass Foo object in Option B when it's not used? – Samurai Apr 29 '15 at 01:11
  • No difference, other than code style / clarity – Bohemian Apr 29 '15 at 01:26
  • @Samuari I meant to do object.var++. This does bring up another question though, if I modify an instance variables it changes its value for all objects? – user4844298 Apr 29 '15 at 01:28
  • 1
    you should never use a static field in a instance context, so both options should create compiler warnings when you use `foo.var` as it is a clear sign for wrong usage. Assigning a static variable in an constructor is also highly dubious. I suspect you dont want to make var static, otherwise the code is pretty pointless. In all places `Foo.var++;` can be used (which makes it clear the object is not used in B). – eckes Apr 29 '15 at 01:37
  • maybe it's not late to read [why-are-static-variables-considered-evil](http://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil) – harshtuna Apr 29 '15 at 02:06

1 Answers1

0

To reinforce what @eckes mentioned above -

There's more common in those samples than different - both are obscure and promote bad practice Understanding Class Members

Note: You can also refer to static fields with an object reference like

myBike.numberOfBicycles

but this is discouraged because it does not make it clear that they are class variables.

Clean way to increment a static variable in this case: Foo.var++ And in a real life example it's usually wrong to have mutable static variables. Especially if your're a beginner.

Community
  • 1
  • 1
harshtuna
  • 757
  • 5
  • 14