Code Pumpkin

final keyword in Java

May 14, 2017
Posted by Pumpkin
Subscribe

final is a keyword in Java. It can be used with variable, method or class. In this article we will see how we can make variable, method or class final in java and what are the advantages of doing so.

If we make a method final, we can not override it in subclass.If we make the class final it can not be sub classed.Making a class final also makes all of its method final. final keyword helps us to write immutable classes which are critical for designing thread-safe multi-threading system which will reduce the amount of synchronization required. To know more about immutable class you can go through our article How To Create Immutable Class In Java.

Lets go through some of examples for final variable, final method and final class.

Final Variable:


public static final boolean REQUIRED = true;
REQUIRED = true; //invalid compilation error

Once we assign value to final variable we can not change its value. If we make a collection final its reference can not be changed but we can add, remove  or change the object inside the collection as shown in below example.


final List<String> nameList = new ArrayList();
//valid
nameList.add("Code Pumpkin");  
//valid
nameList.add("Code Cheif"); 
//Invalid as we can not change the collection reference
nameList = new LinkedList<>(); 

Final Method:


class Bike {
	final void start() {
		System.out.println("kick start");
	}
}

class Honda extends Bike {
	void start() {
		System.out.println("self start");
	}

	public static void main(String args[]) {
		Honda honda = new Honda();
		honda.start();
	}
}

Here, we have declared start method in bike as final. so while extending the Honda class with bike we can not override the start() method. So, our program will give compilation error.

Final Class:

Now lets modify above example and make the Bike class final.


final class Bike {
	void start() {
		System.out.println("kick start");
	}
}

//Can not extend final class. Code will not compile
class Honda extends Bike {
	void start() {
		System.out.println("self start");
	}

	public static void main(String args[]) {
		Honda honda = new Honda();
		honda.start();
	}
}

In above example, when we try to extend bike class the compiler will give error that we can not extend final class.

We can say that we can prevent subclassing by making our class final. However, there is also an alternate way to prevent subclassing using private constructor.

Benefits of final keyword:

  • Final keyword improves performance as JVM cache the final variables. Making a class, method or variable final in Java helps to improve performance because JVM gets an opportunity to make assumption and optimization.

  • Immutable Class can be created with the help of final keyword.

  • Final variables are safe to share in multi-threading environment without additional synchronization overhead.

  • Final keyword allows JVM to optimized method, variable or class

Important points about final keyword:

  • Final keyword can be applied to member variable, local variable, method or class in Java.

  • Final member variable must be initialized at the time of declaration or inside constructor, failure to do so will result in compilation error.

  • You can not reassign value to final variable in Java.

  • Final class can not be inheritable in Java.

  • Local final variable must be initializing during declaration.

  • Only final variable is accessible inside anonymous class in Java.

  • Final method can not be overridden in Java.

  • All variable declared inside java interface are implicitly final.

  • Making a java collection reference variable final means only reference can not be changed but we can add, remove or change object inside collection.

That's all about final keyword in Java. For other java keywords articles, please go to Java Keywords. If you guys have any suggestions or queries, feel free drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here

Happy Learning 🙂


Further Reading For interview Preparation

  1. interface VS abstract class
  2. Access Modifiers (public, private, protected and default scope)
  3. What is the use of private constructor in java?
  4. transient Keyword
  5. HashMap vs Hashtable Vs SynchronizedMap Vs ConcurrentHashMap
  6. How does HashMap work internally in Java? 
  7. How is HashSet implemented internally in Java?
  8. CountDownLatch Vs CyclicBarrier
  9. How To Create Immutable Class In Java

Tags: , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.

Total Post : 80
Subscribe
Contribute Your Articles

Interview Experiences

Related Books

Like Us On Facebook

Alexa Page Rank