I\'m always confused between static
and final
keywords in java.
How are they different ?
The two really aren't similar. static
fields are fields that do not belong to any particular instance of a class.
class C {
public static int n = 42;
}
Here, the static
field n
isn't associated with any particular instance of C
but with the entire class in general (which is why C.n
can be used to access it). Can you still use an instance of C
to access n
? Yes - but it isn't considered particularly good practice.
final
on the other hand indicates that a particular variable cannot change after it is initialized.
class C {
public final int n = 42;
}
Here, n
cannot be re-assigned because it is final
. One other difference is that any variable can be declared final
, while not every variable can be declared static.
Also, classes can be declared final
which indicates that they cannot be extended:
final class C {}
class B extends C {} // error!
Similarly, methods can be declared final to indicate that they cannot be overriden by an extending class:
class C {
public final void foo() {}
}
class B extends C {
public void foo() {} // error!
}