The final Keyword Revisited in Java


The final keyword can also be used to prevent method overriding and inheritance.

Source Code

public class Animal {
    public final void eat() {
        System.out.println("This animal eats.");
    }
}

final class Dog extends Animal {
    // Dog class cannot be subclassed further
}

Use final on methods to prevent them from being overridden by subclasses, and on classes to prevent them from being extended.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments