In a programming language, there is a way to tell the compiler that a piece of data is immutable. There are two requirements
1. A compiler constant that never changes
2. A value that is initialized at run time, and this value is not changed
In Java , these two requirements are implemented using the final modifier variable
<pre name= "code" class= "java" >//compiler constant
private final int valueone = 9;
private static final int value_two =;
public static final int value_three =;
The value that is initialized at run time and the value is not changed
private final int i4 = Rand.nextint;
static final int int_5 = Rand.nextint (m);</span>
Keep data constant when final modifies basic data types
When final modifies an object reference, makes the reference constant. Once a reference is initialized to an object, it cannot be changed to point to another object.
However, the object itself can be modified
The parameter in the final decorated method parameter list means that you cannot change the object that the parameter reference points to in the method. This feature is mainly used to
Anonymous inner class pass data
In addition, in Java
Final cosmetic method, which is intended to explicitly prohibit subclasses from overwriting this method
Final modifier class, prohibiting inheritance
How do you achieve both of these requirements in C #?
Requirement 1: Compiler constants
A const modifier constant that must be available for evaluation at compile time. Constants are always static but do not have to (in fact, are not allowed) to include modifier static in a constant declaration
Requirement 2: Run-time constants
readonly keyword
Sometimes you may need a variable whose value should not be changed, but the value is unknown before you run it.
C # provides another type of variable for this scenario: a read-only field
Also, in C #
Sealed modification method to explicitly prohibit subclasses from overwriting this method
Sealed modifier class, prohibit inheritance
The above is a small series for everyone to talk about the final keyword in Java and C # in the const, readonly keyword All content, I hope we support cloud Habitat Community ~