Vaibhav G Garg wrote:i. If the class is marked as final, then why do we need to mark the methods as final since anyways we can't subclass this class.
JLS 8.4.3.3JLS Chap8 Sec4 wrote:A private method and all methods declared immediately within a final class (ยง8.1.1.2) behave as if they are final, since it is impossible to override them.
Vaibhav G Garg wrote:ii. If the fields are already private, then what is the use of making the methods as final since anyways we can't access the properties in subclasses.
Steve
Steve Luke wrote:Note that the opposite is not true. You can't make the methods all final and not the class.
a subclass could use a member variable of its own and override the getter methods to use this different variable the subclass does have access to.
i. If the class is marked as final, then why do we need to mark the methods as final since anyways we can't subclass this class.
ii. If the fields are already private, then what is the use of making the methods as final since anyways we can't access the properties in subclasses.
Vaibhav G Garg wrote:1. If the variable is marked as private and final, then I assume that we can't change the value of a variable, so, why do we need to mark the method as final?
Carles Gasques wrote:
ii. If the fields are already private, then what is the use of making the methods as final since anyways we can't access the properties in subclasses.
You still can have access to private methods through reflection.
Campbell Ritchie wrote:There is still another pitfall which I haven't mentioned.
Campbell Ritchie wrote:Agree. You need to take a defensive copy of any mutable reference types, which includes arrays, whenever they go into your class (constructor) or come out (getXXX methods).
Jeff Verdegan wrote:So the rules in the OP should have included:
v. If any mutable fields are exposed to the outside world, their contents must be copied to a new object first, and that object, not the field, must be what's exposed.
Mike Simmons wrote:
Jeff Verdegan wrote:So the rules in the OP should have included:
v. If any mutable fields are exposed to the outside world, their contents must be copied to a new object first, and that object, not the field, must be what's exposed.
I think "mutable field" is misleading here; it sounds to me like it could refer to any non-final field. I think you mean: a field which references a mutable type. Such as an array or a StringBuilder, but not a String.
If you make all fields final, rule ii becomes irrelevant.
Jeff Verdegan wrote:I've often wished there was an immutable keyword or something in Java. I suppose it could be done with annotations. There are times when it would be nice to look at either a class or a particular instance of a class, and know (without having to dig into its source and the source of all its fields) that it will be immutable.
Consider Paul's rocket mass heater. |