On the final keyword in Java and const and readonly keyword in C

  • 2020-05-12 02:34:24
  • OfStack

In programming languages, there is a way to tell the compiler that a block of data is constant. There are two requirements

1. An immutable compiler constant
2. A value that is initialized at run time and is not changed

In Java, these two requirements are implemented using the final modification variable


<pre name="code" class="java">// Compiler constant 
private final int valueOne = 9;
private static final int VALUE_TWO = 99;
public static final int VALUE_THREE = 39;
// The value that is initialized at run time and is not changed 
private final int i4 = rand.nextInt(20);
static final int INT_5 = rand.nextInt(20);</span>

final modifies basic data types by keeping the data constant
When modifying an object reference, final makes the reference constant. Once a reference is initialized to point to one object, it cannot be changed to point to another object.
However, the object itself can be modified

final modifies the parameter in the method parameter list, meaning that the object to which the parameter reference points cannot be changed in a method. This 1 property is mainly used to
Anonymous inner classes pass data

Also, in Java

final modifies the method to explicitly prohibit subclasses from overriding the method
final modifies a class to prohibit inheritance

How are these two requirements implemented in C#?

Requirement 1: compiler constants

const modifies constants that must be computable at compile time. Constants are always static but it is not necessary (in fact, not allowed) to include the modifier static in the constant declaration

Requirement 2: runtime constants

readonly keyword
Sometimes you may need 1 variable whose value should not change, but whose value is not known until it is run.
C# provides another type of variable for this situation: a read-only field

Also, in C#

sealed modifies the method to explicitly prohibit subclasses from overriding the method
sealed modifies the class to prohibit inheritance


Related articles: