If we have a private final instance variable to be passed to a private method, do we redeclare it with final modifier in the function when passed as parameter ? eg:
public class GraphAlgo {
private final source;
public GraphAlgo(source) {
this.source = source
}
public void runAlgo() {
runAlgoUsingSource(source);
}
private runAlgoUsingSource(final source) { // here final is declared on a final field
//-- whatever.
}
}
Dont declare final for a parameter which is already a final.
Advantage. prevents duplicate final modifier
Disadvantage: Does not provide explicit picture, eg: if GraphAlgo is a 10000 line code then simply looking at the function 'runAlgoUsingSource' he would not have visual access to understand if 'source' was final or not.
Whats the general convention in this case ?
Here, source is already an instance variable. Why pass it to a method? For that matter, here,
private runAlgoUsingSource(final source) {
source is now another variable, scoped as a local variable, and named the same as your instance variable. (It also needs a type.) Whether this local source is final does not depend on whether this.source (the instance variable) is final.
No, Use final liberally.
One is for an instance variable:
private final SomeType source;
and the other is for a method:
private runAlgoUsingSource(final SomeType source) {
The first says that the instance variable cannot be changed (if it's a reference it cannot refer to a different object), the second says that the method argument cannot be changed.
This isn't a matter of convention; the two final declarations mean different things. Even if the value of a field flows into a parameter, the field can be final and the parameter non-final or vice versa.
It's a matter of debate, but my view is that you should only declare a parameter final if you need to -- and basically the only reason you need to declare a parameter final is if you use its value in an anonymous inner class. Fields, on the other hand, should be final unless you explicitly want to modify them.
The two final modifiers aren't related. One's making the instance member living on the heap final. The other's making a method's local variable (which just happens to share the same name) and is on the stack final.
Marking a method local variable final lets JVM optimise certain things (because it now knows the method does not modify it) and is a good practice. Marking the instance member final goes more on the lines of declaring an actual constant.
Related
In java, constants as known as keyword (final) with a value that will never change. I have seen some people create constants without declaring a static modifier. My question is, should constants be declared as a static? If so or if not, why?
If you assign a value to the final variable when declaring it, there's no point in it not being static, since each instance would have its own variable having the same value, which is wasteful.
However, if you need an instance variable whose value can only be set once (but different instances may have different values), that variable would have to be final but not static.
For example :
class Person
{
final int id;
public Person(int id) {
this.id = id;
}
}
You will first need to understand what constants do (i.e, what happens when you mark a field / local variable as final.)
When a primitive / String field is marked as final, it becomes a compile-time constant i.e, its value is passed as part of the bytecode itself. Thus its value is not computed / generated at runtime. This gives you a performance benefit.
The keyword static is used to say - this field is NOT unique for each instance of a class. You could have non-static final constants as well. Also, if a method local variable (primitive) is marked as final, it also becomes a constant.
So, No, static has nothing to do with constants. It is a design choice.
Constants with the final keyword will never change.. actually you cannot change the instance this field is referencing, but you can change values inside this instance.
Imagine this example:
class SomeClass {
final Car MYCAR;
...
}
With this code you will not be able to change the reference of MYCAR:
MYCAR = new Car(.....);
But you can do something like:
MYCAR.setPrice(10000);
So yes, there is a point in NOT making this field static if any instance of SomeClass needs to have their own copy of the object MYCAR but you don't want anyone to change the reference of this object.
Whatever you like. I would personally use static. You don't need to create an object when you declare it static. Also you can make a 'constants' file, where you store all constants like. public final static ...
So you basically use static final if it's a 'constant' used by all objects. If not, just make it final and pass it through the constructor.
Technically, the keyword final is enough for a constant since you can't change the value of final variables once assigned.
static should be used if the constant is not tied to a particular object instance.
For example, consider you have a Circle class, and you have a method to calculate area. You need the constant Pi for this purpose. Pi constant does not change from circle to circle. So it makes sense to declare Pi as a static final.
When you use keyword static in a class the all instances of class. i.e. All objects of a class share the same variable where as If you declare a class as final the it cannot be instantiated ( it's object cannot be created ). So if you declare a variable final then it can be assigned value only once.
Let suppose
class CalculateArea {
final static double PI = 3.1417;
/*write rest of the code to calculate area.
the value of PI will remain constant no matter
how many times its object is made
if you try to override the value of `PI` it will raise an error.
*/
}
What happens when I declare something like:
public static final String forma = "Rectangular";
Isn't it redundant? Being String a final class, what would it change not setting forma as final? For static, I think it is not making any change.
final make sure reference is not assigned to new value.
If you don't make it final, it is valid to assign some other value to forma (or) you can do some operation on Rectangular and assign results back to forma
See String is a final class,and final keyword makes references final not object final.
Final object means it can't be altered but final reference means it can't be assigned to another object after first assignment.
Being final means you can not modify the object String s="hello", "hello" is the string object and it cant be modified, but about s if its a non-final reference and i do thing like:s=s.concat("bing") then, "hello" is taken can concatenated with "bing" object and then assigned to s means "hello" and "bing" objects are not modified they lost their references and non-final reference s is now referring to a new object "hellobing".
I surely wanna help you more if you find this interesting.
For object-types 'final' modifier means that REFERENCE to this object cannot be changed, not it's value!
Isn't it redundant?
No, it is not redundant. It is constant. Every keyword of this statement has meaning. final make it immutable, static make it class variable and public make it globally accessible.
The final keyword is heavily overloaded, and means very different things in different contexts:
On fields and local variables, it indicates that the content of a reference cannot be changed. (This is different from immutability.)
On classes, it indicates that the class cannot be subclassed.
On methods, it indicates that the method cannot be overridden in subclasses.
This question already has answers here:
Why are only final variables accessible in anonymous class?
(15 answers)
Closed 9 years ago.
If I had this anonymous method I should declare x variable as final.
private void testMethod (ListField<BeanModel> listField){
final ListLoader<BeanModel> loader = new PagedListLoader<BeanModel>();
listField.addListener(Events.Attach, new Listener<ListViewEvent<BeanModel>>() {
#Override
public void handleEvent(ListViewEvent<BeanModel> be) {
loader.load();
}
});
}
However, if loader was a class field, it wouldn't be necessary to declare it as final:
public class testClass{
private ListLoader<BeanModel> loader = new PagedListLoader<BeanModel>();
private void testMethod (ListField<BeanModel> listField){
listField.addListener(Events.Attach, new Listener<ListViewEvent<BeanModel>>() {
#Override
public void handleEvent(ListViewEvent<BeanModel> be) {
loader.load();
}
});
//Could I modify loader's reference here, before the method executes?
//loader = null;
}
}
Does anyone know the reason why they guarantee local variables not to change when they're accessed but don't do it for class fields?
Accroding to java docs
An anonymous class has access to the members of its enclosing class.
An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final (Effectively final means that the variable is never changed after it is initialized. Method parameters are often effectually final.)
The reason for this restriction becomes apparent if we shed some light on how local classes are implemented. An anonymous local class can use local variables because the compiler automatically gives the class a private instance field to hold a copy of each local variable the class uses. The compiler also adds hidden parameters to each constructor to initialize these automatically created private fields. Thus, a local class does not actually access local variables, but merely its own private copies of them. The only way this can work correctly is if the local variables are declared final, so that they are guaranteed not to change. With this guarantee in place, the local class is assured that its internal copies of the variables accurately reflect the actual local variables.
The local variable is allocated in the stack, and it will fall out of scope after testMethod(). Making the variable final ensures that it is ok to just pass a reference to it to the anonymous class. If it was not final, a later assignment to it in testMethod() could change the value later with confusing results. (The user might expect the later assigned value used, but that would be impossible).
A field of the parent class, however can be accessed through the parent reference of the anonymous class, so any later assignments can be handled without confusion.
Anonymous classes get local variables implicitly through constructors. That is they get copies of local vars they use. So if we changed variable value in the main code the anonymous class would not see this change. Declaring local vars final helps avoid this ambiguity.
Have a look at Lambdas and Conjures in java.
An anonymous inner class has no information around it - you have to specify that it is final so you can guarantee its existence.
This could be something to do with the nature of a ListLoader but I am unexperienced with using this library.
I hope I pointed you into the right direction.
I'm working with Java 4; some time ago I came across a variable which was declared in a public class as:
final private static Set name = new HashSet(){
{
add(object1);
...;
add(objectN);
}
};
and I needed to add (or remove) objects to it at runtime under some circumstances.
The class had a public constructor which was called before I had to either add or remove objects to said Set.
I thought that final variables were treated as constants so I wouldn't be able to call the .add(object) and .remove(object) methods on it at runtime. But I did it anyway, I created two public methods to perform the add and remove operations, and it worked.
Why? I'd expected it either not to compile or to throw some kind of exception at runtime.
Can someone explain?
Thank you very much,
best regards
The reference to your name variable is basically a constant and cannot be modified. However, the content of the set can be mutated during runtime as you discovered. To prevent that, you can make it immutable, e.g.
final private static Set name = Collections.unmodifiableSet(new HashSet(){
{
add(object1);
...;
add(objectN);
}
});
You can't change the reference of final variables but you can change the state.
For example:
you can't change reference like name = new HashSet();
The final variables cannot be assigned a new reference after the constructor of the class they belong to has executed. However, you definitely can change their internal state by calling methods on them.
I've got two classes below. Both have one variable 'reply' with a getter. There is no setter method for this variable. Only difference is in ClassOne, the variable is static final.
So whats the difference and which one is preferred?
public class ClassOne {
private static final String reply = "Success";
..
public String getReply() {
return reply;
}
// no setter
}
and Class 2
public class ClassTwo {
private String reply = "Success";
..
public String getReply() {
return reply;
}
// no setter
}
UPDATE 1:
What I want to know is that when there is no setter for a variable, should the variable be declared as static final for optimization? or does it not matter?
should the variable be declared as static final for optimization?
final certainly, not only for optimization but for clarity and because it can make your object immutable, which is always a good thing to have.
static completely changes the nature of the field and has nothing to do with the existence of setters: do you want only one instance of that field, or do you need one per instance of your class?
Non static example: a Person has a name, which is a constant (for a given person = per instance), so you can use a non static final field, which you only set once when creating a new Person:
private final String name;
Static example: Whenever you don't have a name for a Person, you want to use a default value - that is a global constant which is shared among all persons that don't have a name and you can use a static final field:
private static final String NO_NAME = "John Doe";
When you set the variable as final, you are telling everybody (the compiler, the runtime) that it cannot be changed. This can help a lot with optimizations like inlining all of the occurrences of the variable with its value.
When you have a constant string which can not be changed, you should make it a static final string.
Static means that less memory is needed for instance of the class, because the instances don't need individual copies.
Final allows some optimizations and thus makes your program faster.
There are few things good to know:
final variables can be checked by compiler that they are not accidentally changed.
references to non-static variables are contained in instance so there is small needless memory consumption in addition
static variables are shared across all instances of the same class, so you can be sure that all instances work with the same value
final static variables, especially the Strings are linked in compilation time so they need not to be dereferenced at runtime from the field. Due to that it cannot be changed even by the reflection, because such field is not used at runtime.
Setting the reference to final ensures you can't change the reference. Note however that if the object referred to is mutable then you could still change that (not in this instance, since Strings are immutable).
I normally make fields final and initialise them in the constructor. By favouring immutability my classes are easier to debug and are more likely to be safe in threaded environments. It's easier to remove the immutability constraint than add it.
I also do this for method arguments. Rarely (ever) do I want to change a method argument, and making them final will catch inadvertent assignments.
I try not to use static except for final constants. Unless it's something like a logger, I don't really want one instance per class, and (of course) this doesn't work in the case of multiple classloaders. It's also getting close to the singleton anti-pattern, and this impacts on easy testing and (potentially) threading.
The fact that you make the variable static means that a single instance of that variable will be shared among all the instances of ClassOne, as the variable is bound to the class itself, not to its instances. Apart from any JVM optimisations, you'll have a single instance of reply for every instance of ClassTwo.
First one is Constant you need to know value of it at compile time.
private static final String reply = "Success";
second is just simple member variable. So any case first one is preferred since second one will create value for each object.
Assuming that you intended **private final String reply** in second case
A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable.
In second case you can also declare and initialize it in constructor
private final String reply;
You can read more about it here