How to Use Final Keyword in Java


In this example we will show how to use final keyword in Java.

Source Code

1) variable modifier

package com.beginner.examples;

public class FinalExample1 {
   
	final double PI = 3.14;
	
	public FinalExample1() {
		PI = 3.1415926; //The final field FinalVariableExample.count cannot be assigned
	}    
}

Output:

Unresolved compilation problem

2) method modifier

package com.beginner.examples;

public class FinalExample2 {

	final void test(){
		System.out.println("OK");
	}

}

class example extends FinalExample2{

	//Cannot override the final method from FinalExample2
	void test(){
		System.out.println("Done");
	}

}

Output:

Unresolved compilation problem

3) class modifier

package com.beginner.examples;

public final class FinalExample3 {

	final void test(){
		System.out.println("OK");
	}

}

//The type FinalClassChild cannot subclass the final class FinalExample3
class example extends FinalExample3{

	void test(){
		System.out.println("Done");
	}

}

Output:

Unresolved compilation problem
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments