final keyword in java

To do :

  • final keyword can be applied on which all keyword
  • how to make a immutable class
  • final interview questions
  • can you overload a final method
  • blank or uninitialized final variable and usefulness in memory
  • static blank final variable
  • can we declare a final constructor
  • can a inner class be final

Final keyword can be applied on

  • variable
    • Blank final variable
    • Blank final static variable
  • method
  • class
  • objects

Final keyword is applied in java so that it cannot be changed further down the line nor by inheriting the same.

Final variable :

  • A final variable once assigned a value cannot be changed.
  • A final variable that is not initialized at the time of declaration is known as blank final variable.
  • A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.

When a compilation error is thrown in final instance variable ?

  • When an final instance method is not initialized, this instance variable can be initialized by
    • Directly assigning a value.
    • Initializing it via constructor (If once done should be done is all constructors else compilation error)
    • Initializing it in the instance initializer block.
  • Note : If final instance variable is assigned value in any one of the above three ways then it cannot be reassigned Example : If the final instance variable is assigned value in instance initializer block then it cannot be reassigned in the constructor block

When a compilation error is thrown in final static variable ?

  • When an final instance method is not initialized, this instance variable can be initialized by
    • Directly assigning a value.
    • Initializing inside a static block
  • Note : If final static variable is assigned value in any one of the above two ways then it cannot be reassigned Example : If the final static variable is assigned value directly then in static block then it cannot be reassigned.

Final method :

  • Once you make a method final you cannot override it.(Note but it can be overloaded)
  • Once you declare a parameter of a method as final then you cannot change the value of that parameter in that method

Final class :

Once you make a class final you cannot extend it

Final Object (reference):

  • You can modify the properties (instance variable data) of an object but you cannot reassign a new object to that reference.
class Employee {
	public int value = 5;
}

class Demo {
	public static void FinalReference(String args[]) {

		final Employee example = new Employee(); // declaration
		example.value = 6; // Modifying the objects properties creates no disturbance

		Employee another = new Employee();
		example = another; // Attempting to change the objects reference creates a compilation error
	}
}

Final keyword cannot be applied on :

  • Constructor
  • abstract class and interface

Leave a Comment