final keyword in Java

We all know the usage of final keyword in Java:

  1. Classes modified by fiinal cannot be inherited.
  2. A method modified by final cannot be overridden.
  3. Variables modified by final cannot be modified.

        However, variables modified by final cannot be modified. How to understand this? Is it that the value of the variable cannot be modified, or the reference cannot be modified? Can the referenced object be modified? Let's look at the code:

package com.yuwl.jdk;
/**
 * Test content: final modified variable
 * @author Yuwl
 * 2018-3-18
 */
public class FinalTest {

	private final int one = 1;
	private final Value two = new Value(2);
	private final int[] array = new int[]{1,2,3,4};
	
	public static void main(String[] args) {
		FinalTest ft = new FinalTest();
		//ft.one = 2; //The value of the variable modified by final cannot be changed, and the compiler reports an error
		
		Value v3 = new Value(3);	
		//ft.two = v3; //The reference modified by final cannot be changed, and the compilation reports an error
		
		int n = ft.two.setValue(3); //The reference modified by final cannot be changed, but the content of the referenced object can be modified
		
		int[] array2 = new int[]{1,2,3,4,5};
		//array = array2; //The array reference modified by final cannot be changed, and the compilation reports an error
		
		ft.array[1] = 5; //The array reference modified by final cannot be changed, but the contents of the referenced array can be modified
	}

}

class Value {
	
	private int i;
	
	public Value(int i) {
		this.i = i;
	}
	
	public int setValue(int num) {
		this.i = num;
		return this.i;
	}
}

 Through the above code test, it can be concluded that the variable value modified by final cannot be modified by the reference, but the referenced object can be modified.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326189737&siteId=291194637