CodeBlanks Logo Icon CodeBlanks

final class and method

Learn non-extendability with final.

final class

If you mark a class as final, no class can inherit from it. This ensures the class's behavior cannot be changed. Many Java classes like String and Integer are final.

Example: final class Seal { }. You cannot write class Sub extends Seal { }; you get a compile error. final classes are used for security and consistency; they prevent the class design from being broken. They are common in value classes and immutable structures.

final method

If you mark a method as final, subclasses cannot override it. This ensures the method's behavior does not change. Even if the class itself is not final, some of its methods can be final.

Example: class Animal { final void breathe() { } }. A subclass inheriting Animal cannot override breathe with @Override. This prevents critical behavior from being broken. final methods can also be a performance advantage; the compiler can turn them into direct calls.

Practice Add a final method to Animal

Define a class Animal. Add a String name field. Add a final void describe() method; its body writes System.out.println(name + " is an animal");. In main create an Animal instance, assign name and call the describe method.

Starter code

Main.java
// Define the Animal class
// Add a final describe method
// Instantiate and call in main

Sample solution

Main.java
class Animal {
    String name;
    final void describe() {
        System.out.println(name + " is an animal");
    }
    public static void main(String[] args) {
        Animal a = new Animal();
        a.name = "Tiger";
        a.describe();
    }
}

Expected output

Tiger is an animal

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 final class Seal is defined. Which does not compile?

  • Seal s;
  • Seal s = new Seal();
  • class Dog { }
  • class Sub extends Seal { } Correct answer

Explanation: A final class cannot be inherited; extends is not allowed.

2 Match the final uses

Term Meaning
final class Cannot inherit
final method Cannot override
String Final class example
breathe Final method example

3 Complete the final method definition

Question
class Animal {
    ____ void breathe() {
        System.out.println("Nefes");
    }
}
Answer
class Animal {
    final void breathe() {
        System.out.println("Nefes");
    }
}

Explanation: A final method cannot be overridden.

All lessons in Intermediate