views:

441

answers:

2

In Java final applies to more than just a class.

So, I wonder: is there any functional difference between the two keywords?

Thank you, and sorry for a relatively noob question.

A quick Google search did not satisfy my needs.

+2  A: 

Take a look into this answer: What is the equivalent of Java’s final in C#?

Rubens Farias
+6  A: 

Java's final keyword is the equivalent of C#'s sealed, readonly, and sealed keywords.

Two of those three are somewhat different in Java and C#:

In Java, methods are virtual by default, so any method can be declared final to prevent it from being overriden. In C#, methods are not virtual by default, so the only overridden methods can be declared sealed (To prevent them from being further overridden)

In Java, any variable or field can be declared final to prevent it from being changed after initialization (And, for fields, outside the constructor). In C#, fields can be declared readonly, for the exact same effect, but local variables cannot. Note that Java has no equivalent of C#'s const keyword. (consts in C# are evaluated at compile-time, and the values are hard-coded instead of being referenced)

For classes, C#'s sealed classes and Java's final classes are exactly the same (AFAIK).

SLaks
@Matthew: That was not a typo. C# has two different uses of the `sealed` keyword. In VB, they are `NotInheritable` and `NotOverridable`
SLaks
@SLaks, I find the answer somewhat confusing, which is why I thought it was a typo. `sealed` is one keyword with multiple contextual meanings (like many keywords, including `final`, `default`, `using`, etc.). C# `const` is used many places where Java would use `static final`; thus, I think it should be listed atop as one of the equivalents.
Matthew Flaschen
@Matthew: **No**. `const` in C# is _not_ equivalent to `static final`.
SLaks
@SLaks, I am aware there is not a 1 to 1 mapping (final is also used in the other ways you listed), which is why I said "many places". But if you have a Java constant like `private static final int MY_NUMBER = 3` (which is of course quite frequent), I believe `private const int MY_NUMBER = 0;` is the best mapping to C#; of course, you can not use static with C# constants. So `const` is the closest equivalent to *some* uses of `static final`.
Matthew Flaschen