Use the final keyword to do the following:
. declaring a class
When you use final to decorate a class, the class cannot be inherited
Final class Example{int Value;public int getValue () {return value;}} The test here wants to inherit example, but example is final, so the compiler will error class test extends example{}
. Declaring a method
When you use final to modify a method of a class, the method cannot be overridden by a quilt class
Class example{int value;final public int getValue () {return value;}} Class Test extends Example{public int getValue () {}}//The test class here attempts to override the method Example () of the parent class GetValue, but in the parent class GetValue () uses the final decoration, An error is reported that cannot overwrite the parent class method
. Declaring a constant
Class Example{final int value = 100; final int value1;public int setValue () {value = 200;return value;}} The value in the class uses the final decoration, stating that value is a constant, and the method SetValue () attempts to modify the value of values by reporting an error that cannot specify a value for the final variable value during compilation.// In addition, the final modified value1 initialization is not assigned, also error, because it is a constant, cannot have no value, this situation can be assigned in the construction method, the following class example{final int value; Example (int value) {this.value = value; }}//Note that only a construction method can assign a value to an uninitialized final variable
The final keyword in Java