Sobes.tech
Junior — Middle

Explain what it means to declare a class as final in Java and how it differs from a regular class.

sobes.tech AI

Answer from AI

Declaring a class as final in Java means that this class cannot be inherited — that is, you cannot create a subclass from this class. This differs from a regular class, which can be extended and used as a base for new classes.

Main features of a final class:

  • It prohibits inheritance, helping to protect the implementation from changes.
  • It can be used to enhance security and performance (the compiler can optimize method calls).
  • Often used for classes that are not intended to be extended, such as String.

Example:

public final class ImmutableClass {
    private final int value;

    public ImmutableClass(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

// Attempting to inherit will cause a compile error:
// public class SubClass extends ImmutableClass {} // Error

Thus, a final class guarantees that its behavior remains unchanged through inheritance.

Explain what it means to declare a class as final in… - sobes.tech