开发者

Compared to C#, Java's final is similar to const or readonly [duplicate]

This question 开发者_运维知识库already has answers here: What is the equivalent of Java's final in C#? (7 answers) Closed 3 years ago.

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜