Search code examples
javaclassextendfinal

'final' modifier on a class in Java


I have a quick and simple question. I have a habit of making every class 'final' unless of course, it needs to be extended by another.

Is this a bad habit? A good habit? Does it even matter? I understand the effect of the modifier to a class.

Thanks a lot in advance!

Edit: Here is an example code. This class will not be extended by any other classes.

public final class Application {

    /**
     * Starts the application.
     * 
     * @param arguments arguments provided from command-line
     */
    public static void main(String[] arguments) {
        LaunchUtilities util = new LaunchUtilities(new EventHandler());

        try {
            util.addListener(43594);
        } catch (IOException ioe) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, "Could not bind a port to a listener!", ioe);
        }

        util.start();
    }
}

Solution

  • I'm going to say bad habit, for the following reasons:

    • You have not specified any particular need for the class to be final.
    • You are violating the open/closed principle. Classes should be open for extension, but closed for modification.
    • Finalized classes can be difficult to test with mocking frameworks.

    For example:

    public static void main(String[] args) {
        final Fruit mockFruit = Mockito.mock(Fruit.class);
    }
    
    private static final class Fruit {
    
    }
    

    ...will yield...

    Exception in thread "main" org.mockito.exceptions.base.MockitoException: 
    Cannot mock/spy class org.foo.Foo$Fruit
    Mockito cannot mock/spy following:
      - final classes
      - anonymous classes
      - primitive types
    

    Of course, there are valid scenarios for finalizing classes. For example, your class is immutable.