Search code examples
javafinal

Proper use of final


Possible Duplicate:
Java final modifier

This is just a small question about preferences. What would be the correct usage for the final modifier?

I have noticed that going from source-to-source that I tend to use it more than others. I put it for the parameters for a method, for variables in the method and what ever I can. Is that necessary or am I just overdoing it?

Reference:

private final int x;
private final int y;
private final int id;
private final int width;
private final int height;

public Widget(final int id, final int x, final int y, final int width, final int height) {
    this.id = id;
    this.x = x;
    this.y = y;
    this.xmod = x;
    this.ymod = y;
    this.width = width;
    this.height = height;
}

Solution

  • Yes, you are overdoing it. Historically, this might have resulted in some optimizations -- e.g. final methods can be inlined more easily -- but these days, most of those optimizations are done whether or not you actually label the method final.

    The places you should still use final are on most fields in classes, on classes that shouldn't be, or aren't, extended, on methods you don't want overridden, and on local variables that need to get referenced in anonymous inner classes.

    In particular, it is overkill to do it on local variables and on method parameters that will not get wrapped in anonymous inner classes.