0% found this document useful (0 votes)
31 views16 pages

Understanding the Final Keyword in Java

The final keyword in Java can be applied to classes, methods, and variables. It restricts changes to final entities. Final variables cannot be reassigned, final methods cannot be overridden, and final classes cannot be subclassed. The final keyword requires initialization of variables before use to make their values constant and immutable.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views16 pages

Understanding the Final Keyword in Java

The final keyword in Java can be applied to classes, methods, and variables. It restricts changes to final entities. Final variables cannot be reassigned, final methods cannot be overridden, and final classes cannot be subclassed. The final keyword requires initialization of variables before use to make their values constant and immutable.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Final Keyword in Java

The final keyword in java is used to restrict the user. The java final keyword can be
used in many context. Final can be:

Final is the modifier applicable for classes, methods and variables.

1) Java final variable:-

If you make any variable as final, you cannot change the value of final variable(It
will be constant).

Ex:-

class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
[Link]();
}
}//end of class
Output: Compile Time Error.
2) Java final method

 If you make any method as final, you cannot override it.


 Whatever the methods parent has by default available to the child.
 If the child is not allowed to override any method, that method we have to
declare with final in parent class. That is final methods cannot overridden.

Example:
Program 1:
class Parent{
public void property(){
[Link]("cash+gold+land");
}
public final void marriage(){
[Link]("subbalakshmi");
}}
Program 2:
class child extends Parent{
public void marriage(){
[Link]("Pooja");
}}
OUTPUT:
Compile time error.
D:\Java>javac [Link]
D:\Java>javac [Link]
[Link]: marriage() in child cannot override marriage() in Parent; overridden
method is final public void marriage(){
Ex-2:-
class Bike{
final void run(){
[Link]("running");
}
}

class Honda extends Bike{


void run(){
[Link]("running safely with 100kmph");
}

public static void main(String args[]){


Honda honda= new Honda();
[Link]();
}
}
Output:Compile Time Error

3) Java final class:-


 If you make any class as final, you cannot extend it.
 If a class declared as the final then we cann't creates the child class that is
inheritance concept is not applicable for final classes.

Example:

Program 1:

final class Parent

Program 2:

class child extends Parent

OUTPUT:

Compile time error.

D:\Java>javac [Link]

D:\Java>javac [Link]

[Link]: cannot inherit from final Parent class child extends Parent

Ex-2:-
final class Bike{

class Honda1 extends Bike{

void run(){

[Link]("running safely with 100kmph");

public static void main(String args[]){

Honda1 honda= new Honda1();

[Link]();

Output: Compile Time Error

Note: Every method present inside a final class is always final by default whether
we are declaring or not. But every variable present inside a final class need not be
final.

Example:

final class parent{

static int x=10;

static

{
x=999;

}}

The main advantage of final keyword is we can achieve security.

Whereas the main disadvantage is we are missing the key benefits of oops:

polymorsim (because of final methods), inheritance (because of final classes)


hence if there is no specific requirement never recommended to use final keyboard.

Q) Is final method inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:

class Bike{

final void run(){

[Link]("running...");

class Honda2 extends Bike{

public static void main(String args[]){

new Honda2().run();

Output:running...

Final instance variables:


 If the value of a variable is varied from object to object such type of
variables are called instance variables.
 For every object a separate copy of instance variables will be created.

For the instance variables it is not required to perform initialization explicitly jvm
will always provide default values.

Example:

class Test{

int i;

public static void main(String args[]){

Test t=new Test();

[Link](t.i);

}}

Output:

D:\Java>javac [Link]

D:\Java>java Test

0
If the instance variable declared as the final compulsory we should perform
initialization explicitly and JVM won't provide any default values. Whether we are
using or not otherwise we will get compile time error.

Example:

Program 1:

class Test{

int i;

Output:

D:\Java>javac [Link]

D:\Java>

Program 2:

class Test{

final int i;

Output:

Compile time error.

D:\Java>javac [Link]

[Link]: variable i might not have been initialized class Test

Rule:
For the final instance variables we should perform initialization before constructor
completion. That is the following are various possible places for this.

1) At the time of declaration:

Example:

class Test{

final int i=10;

Output:

D:\Java>javac [Link]

D:\Java>

2) Inside instance block:

Example:

class Test{

final int i;

i=10;

}}

Output:

D:\Java>javac [Link]

D:\Java>
3) Inside constructor:

Example:

class Test{

final int i;

Test(){

i=10;

}}

Output:

D:\Java>javac [Link]

D:\Java>

If we are performing initialization anywhere else we will get compile time error.

Example:

class Test{

final int i;

public void m1(){

i=10;

}}

Output:

Compile time error.

D:\Java>javac [Link]
[Link]: cannot assign a value to final variable i

i=10;

Final static variables:

 If the value of a variable is not varied from object to object such type of
variables is not recommended to declare as the instance variables. We have
to declare those variables at class level by using static modifier.
 In the case of instance variables for every object a separate copy will be
created but in the case of static variables a single copy will be created at
class level and shared by every object of that class.
 For the static variables it is not required to perform initialization explicitly
jvm will always provide default values.

Example:

class Test{

static int i;

public static void main(String args[]){

[Link]("value of i is :"+i);

}}

Output:

D:\Java>javac [Link]

D:\Java>java Test

Value of i is: 0
If the static variable declare as final then compulsory we should perform
initialization explicitly whether we are using or not otherwise we will get compile
time error.(The JVM won't provide any default values).

Rule:

For the final static variables we should perform initialization before class loading
completion otherwise we will get compile time error. That is the following are
possible places.

1) At the time of declaration:

Example:

class Test {

final static int i=10;

Output:

D:\Java>javac [Link]

D:\Java>
2) Inside static block:

Example:

class Test{

final static int i;

static{

i=10;

}}

Output:

Compile successfully.

If we are performing initialization anywhere else we will get compile time error.

Example:

class Test{

final static int i;

public static void main(String args[]){

i=10;

}}

Output:

Compile time error.

D:\Java>javac [Link]

[Link]: cannot assign a value to final variable i


i=10;

Final local variables:

 To meet temporary requirement of the Programmer sometime we can


declare the variable inside a method or block or constructor such type of
variables are called local variables.
 For the local variables jvm won't provide any default value compulsory we
should perform initialization explicitly before using that variable.

Example:

class Test {

public static void main(String args[]){

int i;

[Link]("hello");

}}

Output:

D:\Java>javac [Link]

D:\Java>java Test

Hello

Example:

class Test{

public static void main(String args[]){

int i;
[Link](i);

}}

Output:

Compile time error.

D:\Java>javac [Link]

[Link]: variable i might not have been initialized

[Link](i);

Even though local variable declared as the final before using only we should
perform initialization.

Example:

class Test{

public static void main(String args[]){

final int i;

[Link]("hello");

}}

Output:

D:\Java>javac [Link]

D:\Java>java Test

hello

Note: The only applicable modifier for local variables is final if we are using any
other modifier we will get compile time error.

Common questions

Powered by AI

The final keyword in Java enhances security by preventing unauthorized modifications. A final class cannot be subclassed, protecting the class's implementation from alteration or misuse through inheritance. Similarly, final methods cannot be overridden by subclasses, thereby safeguarding the integrity of the method's functionality and ensuring consistent behavior throughout the application's lifecycle. This fixed behavior prevents accidental or malicious changes that could lead to security vulnerabilities or unexpected failures. Consequently, while final restricts flexibility, it secures code against unauthorized extensions and overrides .

Declaring a class as final in Java means that it cannot be extended, which means no subclasses can be created. This limits the application of inheritance, one of the key principles of object-oriented programming (OOP). Inheritance is used to promote code reusability and polymorphism, but by using the final keyword, these benefits are restricted. Thus, while final classes provide security by preventing modification and inheritance, they also mean that polymorphism is not applicable, and you miss out on the advantages of OOP, such as code flexibility and reuse .

Declaring variables as final within a method or block means these variables can be initialized only once; after assignment, their value cannot be changed. This constraint is particularly useful when the variable's immutability is necessary to ensure consistency or logical integrity within a method's execution. Use cases include loop constants, maintaining flags whose state should not change, or ensuring that certain intermediate computation results remain consistent. Since the JVM does not provide default values for local variables, they must be initialized explicitly before use, which is crucial to avoid compile-time errors .

Final instance variables must be initialized at the time of declaration or inside a constructor because they must have a constant value assigned once they are created. Unlike other variables, final instance variables are not assigned default values by the Java Virtual Machine (JVM). Therefore, if they are not expressly initialized, a compile-time error will occur. The places where you can initialize these variables are: at the point of declaration, in instance initializers, or within constructor blocks, ensuring they are given a value before the object construction is complete .

The final keyword ensures the immutability of local variables by allowing them to be assigned only once within the method's scope. Once a final variable is initialized, its value cannot change, effectively creating a constant. This immutability is crucial for scenarios requiring operational consistency and avoiding side effects in a program's logic. For example, using final local variables as loop counters ensures that their value remains unaffected by operations inside the loop, enhancing code predictability and safety by preventing accidental variable reassignment or modification .

The final keyword is viewed as disadvantageous in object-oriented programming because it restricts foundational principles such as inheritance and polymorphism. The inability to extend final classes interferes with class hierarchies and reuse through inheritance. Furthermore, final methods reduce polymorphic behavior since subclasses can't modify method functionality to fit specific needs. These constraints limit the design flexibility and extensibility that are hallmarks of robust OOP systems. As such, while offering security, the final keyword contradicts the more dynamic aspects of object-oriented development intended to foster adaptability and code evolution .

When a method is declared as final in Java, it prevents subclasses from overriding that method. This might be beneficial for security purposes, as it ensures the method's behavior remains unchanged across different instantiations, preserving the original implementation. However, it also restricts the flexibility of polymorphism, a core behavioral feature in OOP, since subclasses cannot provide custom implementations for these methods. As a result, the use of final for methods is trade-off between maintaining stability and limiting the expressive capability of subclassing .

A final static variable must be initialized explicitly because the JVM does not provide default values for it. This requirement means it must be assigned a value at the time of declaration or within a static block before the class is fully loaded. If not properly initialized, a compile-time error is encountered. This rigorous requirement ensures the constant's value is consistent across all instances of a class, ensuring it remains unchanged. Mitigating challenges involves ensuring diligent initialization according to the specified rules, i.e., either at declaration or in appropriate static initializer blocks .

In Java, the use of the final keyword for instance variables mandates their initialization at the time of declaration or within the constructor of the class. This ensures that the final variable is assigned a single, immutable value at object creation. The constructor is one of the safe places where initialization can occur, allowing developers to set these variables dynamically at runtime based on the constructor parameters. Failing to initialize these within the constructor ensures a compile-time error occurs, preventing incomplete or invalid object states .

Final local variables within methods differ significantly in initialization requirements compared to final instance or static variables. Local final variables must be explicitly initialized right where they are declared, as no default value is provided by the JVM. In contrast, final instance variables can be initialized at declaration, in instance initializers, or within constructors, offering slightly more flexibility. For final static variables, initialization must occur at declaration or within a static block. The critical difference lies in the lack of default initialization for local variables, necessitating an immediate assignment upon declaration .

You might also like