Java final keyword – Including 15 doubts with answers

Java final keyword – Complete notes on final keyword in java with examples and uses. Learn why to use final keyword with variables, classes and methods in java programs, including answers to 15 doubts with examples and explanations on final keyword in java language. Also, a brief note has been provided if it is mandatory to use in real life applications and its benefits.

Topics covered on java final keyword.

 

What is final keyword in Java and its Usage?

Final keyword in java is used to put restrictions on variables to be modified, class to be extended and a method to be overridden in java applications.
Final keyword enables the compiler to catch some logic errors and prevents accidental misuse of classes and methods.  When you design or write classes and methods, you use final keyword before variables, classes and methods to clearly show your intent. So, if any programmer misuse it accidentally then compiler will flag an error. In fact, using the final keyword in all your code whenever possible is the best practice. Also, final allows the compiler and virtual machine to perform performance optimizations.

Java final keyword – Summary

  • Prevents a variable and method parameters to be modified
  • Prevents a class to be inherited / extended
  • Prevents a method to be overridden

java final keyword

Java final variable and method parameters

We can make a variable and method parameter final using final keyword in java programs, so, that they cannot be modified. Final data members, parameters and local variables cannot be changed once they are initialized.

In below Student class final variable and a final a parameter has been demonstrated. Class final member variable student id is initialized into the constructor. In function f(final int marks), student marks has been made final so if the function is called with an argument then the method f cannot temper the original value.

class Student{
	//final variable cannot be modified  
	final int id;
	//once id initialized it cannot be changed
	Student(int id){
		this.id =id;
	}	
		
	
	public void f(final int marks) {
		
		//marks cannot be modified inside the function
		System.out.println("Id = "+id);
		System.out.println("Marks = "+marks);
		
		//IF you modify final variable complier will flash error
		//id =2345;
		//marks = 1000;
	
	}
	
}

public class Test {

	public static void main(String[] args) {

		int marks = 500;
		int id = 1234;
		Student s = new Student(id);
		s.f(marks);
	}
}

 

 

Java final class -Stops being extended

A final class cannot be extended or inherited. We declare a class with final keyword to make a class final. For example, “final class A {}”. If you think that a class should be not be extended accidentally in java application then make it final.

In below example, duplicate brand class cannot extend Original brand class as it is declared final.

 

//Original brand
final class OriginalBrand{
	
	public void display() {
		
	}
}

//cannot extend original brand
class DuplicateBrand extends OriginalBrand{
	
}

 

 

Java final method – Stop being overridden

If you make a class member function final, then it cannot be overridden in a child or derived class. Note that having a final method does not mean that class should also be final.

In below example Insurance class is a base class and has two methods i.e. final insurance quote method and a non-final process method. Child class insurance agent can override the process method but he cannot override insurance quote method or else compiler will flag an error.

 

// base class
class Insurance {

	// Java final keyword in method - Cannot be overridden by child class
	public final void InsuranceQuote() {
		System.out.println("Insurance quote by company");
	}

	// can be overridden by child class
	public void process() {

		System.out.println("Process Insurance online");

	}
}

// Derived class
class InsuranceAgent extends Insurance {

	// We cannot override it as in base class, it is final

	// public void InsuranceQuote(){}

	// Override process method from base class
	// Insurance
	public void process() {
		System.out.println("Process Insurance offline");
	}
}

 

 

Important note on java final keyword

If we don’t use final class in java programs, it will still work, but, this is the best practice to make a class final, if we think, that the class should not be inherited throughout the program. Or, may be due to some reason we may want to restrict the extension of the class. So, a software programmer cannot extend it accidentally.

If a programmer will try to inherit it unknowingly, compiler will flash an error and warn programmer to analyse the intention behind making the class final and act accordingly. He can ask the respective leader if he really wants to extend it. If he is allowed  to change the final class to a normal class by removing the final keyword before class then he can do so, or he  should write his own definitions in his class rather that re-using the existing final class.

 

Doubts on java final keyword

 

1)Can we create object of final class?

YES, Object of final class can be created. Just purpose of final is to stop a class to be inherited.

 

final class Car {

	public void run() {
		System.out.println("Run...");
	}
}

public class Test {

	public static void main(String[] args) {

		Car c = new Car();
		c.run();
	}
}

Output:
Run…

2)Can final class extend other class?

Yes, a final class can extend another class.

 

class Engine {
	void cc() {
		System.out.println("1000 cc...");
	}
}

final class Car extends Engine {

	public void run() {
		System.out.println("Run...");
	}
}

public class Test {

	public static void main(String[] args) {

		Car c = new Car();
		c.cc();
		c.run();
	}
}

Output:
1000 cc…
Run…

3)Can final class have abstract method?

No, a finial class cannot have an abstract method. If we have an abstract method in a class, means, we want a derived class of it to implement it. But, writing a final class means we don’t want any class to be derived. So, it is contradictory and no meaning of having an abstract method in a final class.

 

final class Car{

	//Cannot have abstract method
	public abstract void color();
	
}

4) Can final class be abstract?

No. A class should be either final or abstract but cannot be both.

5) Can final method be overloaded?

Yes, final method can be overloaded. Just they cannot be overridden in derived class. Note that having final method in a class does not mean that class is also final. You can read polymorphism method overloading in java with example .

 

class Paint {
	final public void color(String color) {
		System.out.println("Draw color :" + color);
	}

	final public void color(String color1, String color2) {
		System.out.println("Draw color :" + color1 + " " + color2);
	}
}

public class Test {

	public static void main(String[] args) {

		Paint p = new Paint();
		p.color("Red");
		p.color("Red", "Green");
	}
}

Output:
Draw color :Red
Draw color :Red Green

6)Can final method be inherited?

Yes, we can inherit final methods. In below example, drawing class has inherited the color method of Paint class which is final.

 

class Paint {
	
	final public void color(String color) {
		System.out.println("Draw color :" + color);
	}
}

//Inherit final method
class drawing extends Paint {

}

public class Test {

	public static void main(String[] args) {

		drawing p = new drawing();
		p.color("Red");		
	}
}

Output:
Draw color :Red

7) Can a final method be abstract?

No, a final method cannot be abstract. Final means stop the method to be overridden in derived class. An abstract method means, force derived class to override and implement it. This is contradictory.

 

class Car{

	//Cannot have abstract method
	public final abstract void color();
	
}

 

8) Can we have a method static and final?

Yes, we can have a final method static.

 

class Car {

	public final static void run() {
		System.out.println("Run...");
	}
}
public class Test {

	public static void main(String[] args) {

		Car.run();		
	}
}

 

9) Can a method be final in abstract class?

Yes, java abstract class can have a final method.

 

abstract class Engine {
	public final void cc() {
		System.out.println("1000 cc...");
	}
}

class Car extends Engine{	

	public void run() {
		System.out.println("Run...");
	}
}

public class Test {

	public static void main(String[] args) {

		Car c = new Car();
		c.cc();
		c.run();
	}
}

Output:
1000 cc…
Run…

10) Can main () method be final?

Yes, the main () can be declared as final.  It doesn’t matter if it is declared final, the JVM will still find it and run it, and the compiler doesn’t complain. If we make main method final just it cannot be overridden in a child class. Note: main() method can be overloaded in java.

 

11) Can we write final method in interface in java?

No, a method can be public, static and abstract in an interface in java but cannot be final. An abstract method cannot be final. Abstract method means force overriding to sub classes and final method means stop overriding that is contradictory.

 

12) Can we declare constructor as final?

No, constructor of a class cannot be final.

 

class Car {	

	//constructor cannot be final
	public final Car(){
		
	}	
}

 

13) Can we declare interface as final?

No, an interface in java cannot be declare as final. Interfaces are meant to be inherited and final declaration will stop it to be inherited.

//cannot make an interface final
final interface IShape{
	 void draw();
}

 

14) Can a variable be final in an Interface?

Yes, all variables are implicitly public static and final in interfaces.

 

15) Can abstract class have final variable?

Yes, an abstract class can have final variable.

abstract class Engine{	
	private final int type;
	//constructor
	//final variable can be initialize into constructor
	//once initialize, final variable cannot be modified
	Engine(){
		type = 1;
	}
	
}

Note that, you cannot instantiate Engine class because it is abstract. But, if you create a non-abstract subclass of Engine, the constructor will be called.



Leave a Comment