5

Wondering if compared to C#, java's final is more similar to which? const or readonly?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user705414
  • 20,472
  • 39
  • 112
  • 155

3 Answers3

12

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

debracey
  • 6,517
  • 1
  • 30
  • 56
7

readonly, because just like in C#, you can only set final once, including within the constructor.

pickypg
  • 22,034
  • 5
  • 72
  • 84
1

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;
}
George Kargakis
  • 4,940
  • 3
  • 16
  • 12