Должны ли поля класса Java всегда быть окончательными? Это хорошая практика?Должны ли поля класса Java всегда быть окончательными? Это хорошая оценка?
Я знаю, что означает «final» для примитива или типа объекта. Мой вопрос в том, должен ли я часто (или всегда) использовать поля с окончательным?
например.
public class MemoryUsage {
private final long init;
private final long used;
private final long committed;
private final long max;
/**
* Constructs a <tt>MemoryUsage</tt> object.
*
* @param init the initial amount of memory in bytes that
* the Java virtual machine allocates;
* or <tt>-1</tt> if undefined.
* @param used the amount of used memory in bytes.
* @param committed the amount of committed memory in bytes.
* @param max the maximum amount of memory in bytes that
* can be used; or <tt>-1</tt> if undefined.
*
* @throws IllegalArgumentException if
* <ul>
* <li> the value of <tt>init</tt> or <tt>max</tt> is negative
* but not <tt>-1</tt>; or</li>
* <li> the value of <tt>used</tt> or <tt>committed</tt> is negative;
* or</li>
* <li> <tt>used</tt> is greater than the value of <tt>committed</tt>;
* or</li>
* <li> <tt>committed</tt> is greater than the value of <tt>max</tt>
* <tt>max</tt> if defined.</li>
* </ul>
*/
Короткий ответ: нет. Длинный ответ: прочитайте документы на 'final'. – Mena
Возможный дубликат [Когда следует использовать final для параметров метода и локальных переменных?] (Http://stackoverflow.com/questions/154314/when-should-one-use-final-for-method-parameters-and-local -переменные) – Unihedron
@Unihedron Как на самом деле это дубликат? OP спрашивает о полях класса. Этот вопрос касается параметров метода и локальных переменных. –