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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With