Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting a static variable in java

Tags:

java

I am new to java hence probably a very noob question:

I have a class

public class Foo{
  private static String foo;
  private String bar;

  public Foo(String bar){
      this.bar = bar;
  }

}

Now before I instantiate any object for class Foo, I want to set that static variable foo. which will be used in the class.. How do i do this?

Also, please correct my understanding. value of foo will be same across all the objects, hence it does make sense to declare it as static ? right?

like image 354
frazman Avatar asked Aug 22 '13 21:08

frazman


1 Answers

public class Foo{
  private static String foo = "initial value";
  private String bar;

  public Foo(String bar){
      this.bar = bar;
  }

}

Since the value will be the same across all objects, static is the right thing to use. If the value is not only static but also never changing, then you should do this instead:

public class Foo{
  private static final String FOO = "initial value";
  private String bar;

  public Foo(String bar){
      this.bar = bar;
  }

}

Notice how the capitalization changed there? That's the java convention. "Constants" are NAMED_LIKE_THIS.

like image 92
Daniel Kaplan Avatar answered Oct 04 '22 19:10

Daniel Kaplan