What is final class and method in Java - onlyxcodes

Wednesday 18 May 2022

What is final class and method in Java

The final keyword in Java is discussed in this post.


In this post, we'll look at what a final class in Java is and how to utilize it. In Java, what is the purpose of the final class?


This tutorial also goes deep into the concepts of a final variable and a final method in Java.


Let's get started.


final class in java - final keyword in java - final method in java - final variable in java

Table Content

1. What is final keyword in Java?

2. What is the final class in Java?

3. How to Create a final class in Java?

4. Final Method in Java

5. Final Variable in Java

6. Initializing Final Variable in Java

7. Change or Reassign the Value of a final Variable

8. final Keyword with an Array Variable

9. final Reference Variable

10. Frequently Asked Questions


Let's start with Java's final keyword.


1. What is final keyword in Java?

The final keyword in Java is a non-access specifier that is used to deny access to a class, variable, or function.


If we use the final keyword to initialize a variable, we can't change its value.


When a method is declared final, it cannot be overridden by any subclasses.


If we declare a final class, subclasses will not be able to inherit it.


Friends, first we'll look at the final class in Java, then we'll talk about final variables and methods.


2. What is the final class in Java?

The final class is a class that is declared with the final keyword.


When a class is declared final, it stops other classes from inheriting or extending it.


All wrapper classes in Java are final classes, such as String, Integer, and so on. We are unable to extend them.


A compilation error will occur if another class attempts to extend the final class.


3. How to Create a final class in Java?

We can build a final class by including the final keyword in the class declaration.


We've developed a final class called A (parent class) in the example below. The final keyword, non-access modifiers, is used here.


Following that, we established the B child class.


We attempted to inherit the final class (A class) from the B class in this example.


We have generated a B class object within the main procedure. We then called the method on that object.


final class A
{
	void message()
	{
		System.out.println("This is a method of final A class");
	}
}

class B extends A
{
	void message()
	{
		System.out.println("This is a method of B class");
	}
	
	public static void main(String args[])
	{
		B obj = new B();
		obj.message();
	}
}

Output:


When we compile the program, we get the following compilation error message.


error: cannot inherit from final A class B extends A

Advantages of the final class


Security reasons: We sometimes write classes that do various authentication and password-related functions that we don't want anyone else to change.


Standardization: Some classes execute standard functions and are not intended to be updated, for example, classes that do string manipulations or mathematical functions.


Java Wrapper Classes: class wrapper The final class is an integer. If that class isn't final, anyone can extend Integer into their own class and change the integer's core behavior. Java makes all wrapper classes final classes to avoid this.


4. Final Method in Java

A method is called a final method when it is declared with the final keyword.


By putting the final keyword before the method name, we can declare Java methods as final methods.


When a method is declared final, it cannot be overridden by any subclasses.


The final method is simply declared below.


final void message()
{
	// method body
}

In the example below, we've added a final method to the A class called message(). The B class inherits the A class in this instance.


class A
{
	final void message() // create a final method
	{
		System.out.println("This is a method of final A class");
	}
}

class B extends A
{
	void message() // try to override final method
	{
		System.out.println("This is a method of B class");
	}
	
	public static void main(String args[])
	{
		B obj = new B();
		obj.message();
	}
}

Output:


The final method in the B class was attempted to be overridden. We get a compilation error with the following message when we compile the program.


error: message() in B cannot override message() in A
        void message() // try to override final method
             ^
overridden method is final

Advantages of Java Final Method.


In Java, the final method is always locked at compile time. Because it does not need to be fixed during runtime, it is substantially faster than non-final methods.


When to use the final method?


Final methods can be used in three different scenarios.


To stop derived classes from overriding the capabilities of a base class.


This is for security reasons, as the base class provides some key framework core functionality that a derived class is not meant to change.


Final and private methods are faster than instance methods since they don't use the virtual table notion. As a result, if possible, attempt to utilize the final methods.


5. Final Variable in Java

We can't change the value of a variable after it's declared using the final keyword. We'll get a compilation error if we try to change the value of the final variable.


A final variable can be thought of as a constant because its values cannot be modified.


You can't change the value of a final variable once it's been initialized if you use the final keyword with primitive types of the variable (int, float, char, etc). As a result, we must initialize it.


The component of an object can be altered if you use the final keyword with non-primitive variables (non-primitive variables are always references to objects in Java).


This indicates we can alter the object's properties but not the object's reference to another object. This will be discussed in the final reference variable section.


We'll start by looking at how to use the final keyword with primitive data types.


Declaration of a final variable


Two things need to be considered while declaring a final variable.


The final keyword is used to declare.


Another point to consider is the variable's initialization.


class Test
{
    public static void main(String args[])
    {
        final int n = 5;
        n = 5+15;
        System.out.println(n);
    }
}

Output:


error: cannot assign a value to final variable n
       n = 5+15;

6. Initializing Final Variable in Java

A final variable can only be initialized once, as we saw in the previous example.


We term it a blank final variable if you don't initialize it while declaring it.


A blank final variable can be initialized in Java in two ways:


1) Initialization with the constructor


2) Initialization with a Static Block


1) Initialization with the constructor


In the constructor of the class, we can create a blank final variable.


Many coders confuse this idea and believe that a constructor can several times initialize the final variable, which is incorrect.


When the JVM calls a constructor, it creates a new object and sets the value of the new object.


If the class contains numerous constructors, you must initialize the final variable in each constructor; otherwise, an error will occur.


package com.onlyxcodes;

class Example 
{
	final int i;

	public Example() 
	{
		i = 50; // We get a compiler error if we remove this code.
	}

	public Example(int a) 
	{	
		this.i = a; // We get a compiler error if we remove this code.
	}
}

class Demo 
{ 
    public static void main(String args[]) 
    { 
    	Example obj = new Example();
        System.out.println("Value of final variable i = "+ obj.i);
        
        Example obj1 = new Example(100); 
        System.out.println("Value of final variable i = "+ obj1.i);
  
        Example obj2 = new Example(150);  
        System.out.println("Value of final variable i = "+ obj2.i);
    } 
}


Output:


Value of final variable i = 50
Value of final variable i = 100
Value of final variable i = 150

2) Initialization with a Static Block


A final variable can be initialized in a static block, but it must also be static.


In the constructor, however, static final variables cannot be set to a value. As a result, they must be given a value along with their declaration.


package com.onlyxcodes;

class Bike 
{
	static final int speed;
	static int km;
	
	static
	{
		speed = 80;
		km = 1;
	}
}

class Demo 
{ 
    public static void main(String args[]) 
    { 
    	System.out.println("Value of final variable speed = "+ Bike.speed);
        System.out.println("Value of final variable km = "+ Bike.km);
    } 
}


Output:


Value of final variable speed = 80
Value of final variable km = 1

7. Change or Reassign the Value of a final Variable

It is not possible to reassign a final variable; doing so would result in a compile-time error.


class Demo
{ 
	final int p = 15;
	
	public void reassignValue()
	{
		p = 25;
	}
    public static void main(String args[]) 
    { 
    	Demo obj = new Demo();
    	obj.reassignValue();
    	System.out.println("Value of p :- "+ obj.p);       
    } 
}

Output:


Demo.java:7: error: cannot assign a value to final variable p
			 p = 25;

8. final Keyword with an Array Variable

We can make a final array variable. The array variable reference cannot be modified. However, the array's elements can be changed.


class Test
{ 
    public static void main(String args[]) 
    { 
        final int arr[] = {10, 20, 30};  
        arr[0] = 100;
        arr[1] = 200;
        arr[2] = 300;
		
        for(int i = 0; i < 3 ; i++ )
        {
            System.out.println(arr[i]);
        }
        
        // You are unable to modify it. There will be a compilation error.
       // arr = new int[5];
        
    }
}

9. final Reference Variable

The value of final variables in Java cannot be modified, as we all know.


We'll look at how the reference variable works with the final keyword in this section.


Consider the code below.


public class Test 
{

	public static void main(String[] args) 
	{
		final int productNumber = 0;
		productNumber = 20; // this not compile
	}
}

Because we are changing the value of productNumber, the compilation is definitely failing because it is the final variable and cannot be modified.


But what if we declare a reference variable to an object to be final? Is it possible to alter its value? Let's see what happens.


Consider the Employee class.


package com.onlyxcodes;

public class Employee 
{
	
	private String name = null;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
}

Now view the Test class as follows


package com.onlyxcodes;

public class Test 
{
	
	public static void main(String args[])
	{
		final Employee emp = new Employee();
		
		emp.setName("Hamid");
		System.out.println("name = " + emp.getName());
		
		emp.setName("Faisal");
		System.out.println("name = " + emp.getName());
	}

}

Output:


This compiles successfully and produces the following output.


name = Hamid
name = Faisal

What gives that this possible? How is it that we can change the value of the emp variable when we've made it final?


The actual meaning of the final keyword is that once a value has been set to the variable, it cannot be changed. Let's see how it compares to the previous example.


We're attempting to assign 20 due to having already assigned the value 0 to productNumber. This is why it fails to compile.


final int productNumber = 0;
productNumber = 20; // this not compile

In our second example,


final Employee emp = new Employee();
		
emp.setName("Hamid");
System.out.println("name = " + emp.getName());
		
emp.setName("Faisal");
System.out.println("name = " + emp.getName());

The reference variable emp refers to an Employee object that we generated.


We gave the Employee object the name "Hamid."


Set Employee's name to "Faisal" once more.


You'll see that the values of the Employee object have only been updated, while the value of the emp reference variable has remained unchanged.


We are not creating a new Employee object and adding it to the variable. The final variable condition is not violated.


If you do,


final Employee emp = new Employee();
emp.setName("Hamid");
System.out.println("name = " + emp.getName());
emp = new Employee(); // it is not compile

After that, as expected, the output does not compile since we are assigning a reference variable to a new Object, which is not permitted for a final variable.


10. Frequently Asked Questions

What is the use of the final keyword in Java?


The final keyword can be used with variables, classes, and methods.


When linked with a class, it disables inheritance by preventing subclass expansion.


This disallows overriding when used with methods, as you can't override a final method in Java.


When used with variables, they are viewed as constants because their value cannot be changed once assigned.


What is a blank final variable?


A blank final variable is one that is not initialized during the declaration phase.


Can we declare the final variable without initialization?


Yes, we can specify a final variable without initializing it, and these final variables are known as blank final variables. However, these final variables must be initialized before being used.


What is the final Modifier in Java?


Once declared, the final modifier in Java has three mechanisms:


Make constants or variables that can't be reassigned, disallow inheritance, and block overriding methods.


What is the main difference between abstract methods and final methods?


Final methods are not suitable for overriding, and abstract methods must be overridden in subclasses.


Final vs Static in Java


StaticFinal
A member variable or method containing the static keyword can be used without having to configure the class to which it relates.The final keyword designates an element to which only one assignment can be made.
It is possible to re-initialize the static variables.It is not possible to re-initialize the final variables.
It can be invoked by other static methods and only accesses the class's static members.Overriding the final methods is not possible.
The object of the static class cannot be generated. It only includes static members.Other classes cannot inherit from the final class.
In a block, the static keyword can be used.A block does not use the final keyword.

Difference Between C++ const variables and Java final variables.


When declaring const variables in C++, they must be given a value. It is not required for final variables in Java, as seen in the examples below. 


A value can be assigned to a final variable afterward, but only once.


class Test 
{
    public static void main(String args[])
    {
        // declaring a final variable locally
        final int p;
 
        // now initialize the value to an integer
        p = 20;
 
        // on the console, show the value
        System.out.println(p);
    }
}

Output:


20

MCQ (Multiple Choice Questions)


What is the use of the final keyword in Java?


a) A subclass of a class that has been made final cannot be created.


b) A method that is final cannot be overridden.


c) A variable can only be assigned a value once when it is final.


d) All of the above


Answer: d

No comments:

Post a Comment

Post Bottom Ad