Java final keyword

The final keyword in Java is a modifier used to impose restrictions on variables, methods, and classes. It is part of the Java programming language to ensure immutability, prevent overriding, and prevent inheritance in various scenarios.

Final Variables:

  • Purpose: A final variable becomes a constant once it is initialized. Its value cannot be changed after being assigned.


Syntax:

final dataType variableName = value;
Example
class Example {
final int MAX_VALUE = 100; // Constant variable

void display() {
// MAX_VALUE = 200; // Compilation Error: Cannot reassign a final variable
System.out.println("MAX_VALUE: " + MAX_VALUE);
}
}

public class Main {
public static void main(String[] args) {
Example obj = new Example();
obj.display();
}
}

Try it yourself


Final Methods:

  • Purpose: A final method cannot be overridden in a subclass, ensuring that the method's implementation remains the same in all derived classes.


Syntax:

class Parent {
    final void display() {
        System.out.println("This is a final method.");
    }
}

class Child extends Parent {
    // void display() { } // Compilation Error: Cannot override the final method
}
Example
class Parent {
final void display() {
System.out.println("Final method in Parent class.");
}
}

class Child extends Parent {
void show() {
System.out.println("Method in Child class.");
}
}

public class Main {
public static void main(String[] args) {
Child obj = new Child();
obj.display(); // Calls the final method from Parent
obj.show();
}
}

Try it yourself


Final Classes:

  • Purpose: A final class cannot be extended, preventing inheritance. It is used to make the class immutable or to prevent modification of its behavior.


Syntax:

final class FinalClass {
    void display() {
        System.out.println("This is a final class.");
    }
}

// class Child extends FinalClass { } // Compilation Error: Cannot inherit from final class
Example
final class FinalClass {
void display() {
System.out.println("This is a final class.");
}
}

public class Main {
public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.display();
}
}

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.