How use final modifier for variable in Java 9 ?

In this article we dive into Java 9 and final modifier . We create in Eclipse with Java 9 project:

and create two classes:

Look at the first example TestFinal class:

public class TestFinal {

	String manName = "Mark";
	final String WOMAN_NAME = "Lisa";

	String getManName() {
		return manName;
	}

	void setManName(String manName) {
		this.manName = manName;
	}

	String getWOMAN_NAME() {
		return WOMAN_NAME;
	}

}

Notice that this class above has only one variable with final modifier. So you can’t change its value after created object. The value is assigned for final variable only once. Look at the main class: Test.java:

public class Test {

	public static void main(String[] args) 
	{
		TestFinal tf = new TestFinal();
		tf.manName = "Gary" ;
		String m = tf.getManName();
		String w = tf.getWOMAN_NAME();
		System.out.println(m+' '+w);
	}

}

We changed only name of man, but for woman it isn’t possible, because name of woman is final.
Result:

What will happen if we only declare the final variable womanName and don’t assign any value. It is known as blank final variable.
Let’s see TestFinal class after modification:

public class TestFinal {

	String manName = "Mark";	
	final String WOMAN_NAME;
	
	String getManName() {
		return manName;
	}
	void setManName(String manName) {
		this.manName = manName;
	}
	String getWOMAN_NAME() {
		return WOMAN_NAME;
	}

}

This class will not be compiled. You see information that must be initialized the value for final variable. What to do?
The blank final variable may be initialized in the constructor of the class. So we may assign value for blank final variable during creating object this class. Look at the another version of this class:

public class TestFinal {

	final String WOMAN_NAME;
	String manName = "Mark";

	public TestFinal(String wName) {
		WOMAN_NAME = wName;
	}

	String getManName() {
		return manName;
	}

	void setManName(String manName) {
		this.manName = manName;
	}

	String getWOMAN_NAME() {
		return WOMAN_NAME;
	}

}

In main class you call object with name of woman:

public class Test {

	public static void main(String[] args) 
	{
		TestFinal tf = new TestFinal("Ellie");
		tf.manName = "Gary" ;
		String m = tf.getManName();
		String w = tf.getWOMAN_NAME();
		System.out.println(m+' '+w);
	}

}

Result:

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.