Java Programming Final Keyword And Access Modifiers Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    6 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Java Programming Final Keyword and Access Modifiers

Java Programming: The final Keyword and Access Modifiers

Introduction

The final Keyword

The final keyword in Java is used to create constants, i.e., values that cannot be modified once they are assigned. It can be applied to variables, methods, and classes.

1. Final Variables

A variable declared as final cannot be modified after its initial assignment. For instance:

final int MAX_VALUE = 100;

This ensures that MAX_VALUE remains 100 throughout the program. If you attempt to change the value, a compile-time error will occur.

2. Final Methods

A method declared as final cannot be overridden by subclasses. This is particularly useful when you want to lock down certain functionality.

public final void doSomething() {
    // method implementation
}
3. Final Classes

A class declared as final cannot be subclassed. This is often used in scenarios where extending a class would lead to unintended side effects.

public final class Constants {
    // class implementation
}

Access Modifiers

Access modifiers control the visibility and accessibility of classes, methods, and variables. There are four access modifiers in Java:

1. public

The public access modifier allows a class, method, or variable to be accessed from any other class in any package.

public class MyClass {
    public void myMethod() {
        // method implementation
    }
}
2. protected

The protected access modifier allows a method or variable to be accessed within the same package and by subclasses, even if they are in different packages.

protected void myMethod() {
    // method implementation
}
3. default (package-private)

If no access modifier is specified, the default access level (package-private) is assumed. The method, variable, or class is accessible only within classes in the same package.

void myMethod() {
    // method implementation
}
4. private

The private access modifier restricts visibility to the class only. It is not accessible from any other class, even subclasses within the same package.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Java Programming Final Keyword and Access Modifiers

The final Keyword

The final keyword in Java is used to declare a constant value. It can be used with variables, methods, and classes to lock down their usage.

  1. Final Variable:
    • Once a final variable is assigned a value, it cannot be changed.
public class FinalVariableExample {
    // Final static variable (constant) declared outside any method block
    public static final int MAX_VALUE = 100;

    public static void main(String[] args) {
        // Final variable declared inside a method block
        final int MIN_VALUE = 10;
        
        System.out.println("Max Value: " + MAX_VALUE);
        System.out.println("Min Value: " + MIN_VALUE);

        // Trying to change the value of a final variable will result in an error
        // MAX_VALUE = 200; // This line would cause a compilation error
        // MIN_VALUE = 5;   // This line would also cause a compilation error
    }
}
  1. Final Method:
    • A final method cannot be overridden in subclasses.
class ParentClass {
    // Final method that cannot be overridden in subclasses
    public final void displayMessage() {
        System.out.println("This is a final method in ParentClass.");
    }
}

class ChildClass extends ParentClass {
    // Attempting to override the final method would result in a compilation error
    // public void displayMessage() {   // This line would cause a compilation error
    //     System.out.println("Trying to override final method.");
    // }
    
    public void anotherMethod() {
        System.out.println("Child class method.");
    }
}

public class FinalMethodExample {
    public static void main(String[] args) {
        ChildClass child = new ChildClass();
        child.displayMessage(); // Calls the final method from ParentClass
        child.anotherMethod();  // Calls method specific to ChildClass
    }
}
  1. Final Class:
    • A final class cannot be subclassed.
// Final class that cannot be extended
final class FinalClass {
    public void displayMessage() {
        System.out.println("This is a final class.");
    }
}

// class AnotherClass extends FinalClass {    // This line would cause a compilation error
//     public void displayMessage() {
//         System.out.println("Trying to extend final class.");
//     }
// }

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

Access Modifiers

Access modifiers in Java determine the visibility and accessibility of classes, methods, and other members. The primary access modifiers are private, default (package-private), protected, and public.

  1. Private Access Modifier:
    • A private member can only be accessed within its own class.

Top 10 Interview Questions & Answers on Java Programming Final Keyword and Access Modifiers

Top 10 Questions and Answers on Java Programming: Final Keyword and Access Modifiers

1. What is the purpose of the final keyword in Java?

Example:

final int MAX_VALUE = 100; // cannot be changed
final class MyFinalClass { } // cannot be subclassed
final void myFinalMethod() { } // cannot be overridden

2. Can you override a final method in Java?

No, you cannot override a final method in Java. The final keyword in Java prevents a method from being overridden in any subclass. This is used when there is a specific implementation in a superclass that must not be changed by subclasses.

Example:

class Parent {
     final void show() {
       System.out.println("Parent Method");
     }
}

class Child extends Parent {
     // void show() { // compile-time error
     //    System.out.println("Child Method");
     // }
}

3. What happens if you try to inherit from a final class in Java?

If you try to inherit from a final class in Java, you will get a compile-time error. The final keyword prevents other classes from extending it.

Example:

final class FinalClass {
      void show() {
         System.out.println("Final class method");
      }
}

class ChildClass extends FinalClass { // compile-time error
      void show() {
         System.out.println("Child class method");
      }
}

4. Can a blank final variable be assigned a value after its declaration?

Yes, a blank final variable (i.e., a final variable that is not initialized during declaration) can be assigned a value in the constructor of the class. This is common when you need to initialize a final variable with a value that is not known at the time of declaration.

Example:

class FinalExample {
     final int value;
     FinalExample(int value) {
         this.value = value; // initialized in constructor
     }
}

5. What are the differences between public, private, protected, and default access modifiers in Java?

  • public: The access level is the most permissive and allows access from anywhere, both within and outside the package.
  • private: The access level is the least permissive and allows access only within the class.
  • protected: The access level allows access within the class, within the package, and from subclasses in different packages.
  • default (package-private): If no access modifier is specified, it is considered default. This allows access within the class and within the same package, but not from subclasses in other packages.

Example:

public class AccessModifiers {
    public int publicVar;       // accessible from anywhere
    private int privateVar;     // accessible only within this class
    protected int protectedVar; // accessible within this class, within same package, or subclasses in other packages
    int defaultVar;             // accessible within this class and within same package
}

6. Can a class have both public and default access modifiers?

No, a class cannot have both public and default access modifiers. A class can have only one access modifier. If no access modifier is specified, the class is considered package-private (default).

Example:

public class MyClass { } // correct
class MyClass { }        // correct (default access modifier)
// public default class MyClass { }  // incorrect

7. What happens if both public and default access modifiers are used for a method or a variable?

Java does not allow using both public and default access modifiers together for a method or a variable. This will result in a compile-time error.

Example:

// public int myMethod() { } // correct
// int myMethod() { }        // correct (default access modifier)
// public default int myMethod() { } // compile-time error

8. How do the access modifiers interact with inheritance in Java?

Inheritance rules regarding access modifiers are as follows:

  • private members of a superclass are not accessible in subclasses.
  • default (package-private) members of a superclass are accessible in subclasses only if they are in the same package.
  • protected members of a superclass are accessible in subclasses, regardless of whether they are in the same package or not.
  • public members of a superclass are accessible in subclasses, regardless of whether they are in the same package or not.

Example:

class Parent {
     private int privateVar;
     int defaultVar;
     protected int protectedVar;
     public int publicVar;
}

class Child extends Parent {
     void accessVariables() {
         // System.out.println(privateVar); // not accessible
         // System.out.println(defaultVar); // accessible only if Child is in the same package as Parent
         System.out.println(protectedVar); // accessible
         System.out.println(publicVar);    // accessible
     }
}

9. How does the final keyword work with method parameters and local variables?

The final keyword can also be used with method parameters and local variables. When a method parameter or a local variable is declared as final, its value cannot be changed after it has been assigned.

Example:

public void myMethod(final int param) {
    // param = 10; // compile-time error
}

public void localVariableExample() {
    final int localVar = 10;
    // localVar = 20; // compile-time error
}

10. Can a final variable be initialized in instance initializer or constructor?

Yes, a final variable can be initialized in an instance initializer or a constructor, but it must be initialized before the object is used or returned from the constructor. For instance variables declared as final, they must be initialized either in the instance initializer, a constructor, or at the time of declaration.

Example:

You May Like This Related .NET Topic

Login to post a comment.