Compared to C#, Java's final is similar to const or readonly [duplicate]
Wondering if compared to C#, java's final is more similar to which? const or readonly?
Interesting question,
Java's final
keyword implies a few things:
- You can only assign the value once
- You must assign the variable in the constructor, or as the part of the declaration
C#'s readonly
keyword applies basically the same restrictions.
For completeness - let's look at const
:
- You can only assign to it once as part of the declaration
- It is inherently static -- there is only one of those for all N instances of your class
So -- I'd say final is more similar to readonly.
-- Dan
readonly
, because just like in C#, you can only set final
once, including within the constructor.
Java's final keyword implements both cases of C# readonly
and const
keywords.
C# readonly
public Employee
{
private readonly string _name;
public Employee(string name)
{
this._name = name;
}
}
Java final (readonly)
public class Employee
{
private final String name;
public Employee(String name) {
this.name=name;
}
}
C# const
public class Circle
{
private const float Pi = 3.14F;
}
Java final (const)
public class Circle
{
private final float pi = 3.14F;
}
精彩评论