Heart containing Coding Chica Java 101

You Shall Not Modify! Final Methods and Classes

TIP: References Quick List

Table of Contents

  1. Table of Contents
  2. Introduction
  3. Final Method
  4. Final Class
  5. Side Effects
  6. Final Variables and Input Parameters
  7. Summary

Introduction

In Java, if we want to prevent child classes (AKA sub-classes) from overriding a particular method, we can add the final keyword to that method’s signature in our class. This might be needed if:

  • A method is called from a constructor,
  • A method is important to state maintenance or other critical details for a given class.

Similarly, if a class as a whole should not have any sub-classes, we can add the final keyword to the class itself.

Final Method

Let’s say we wanted to make our If a method should be marked as final would look like this:

   public final long getAge(final AgeUnits unit) {

Final Class

Similarly, if we wanted to mark the Animal class as final, it would look like:

    public final class Animal {

Side Effects

Making a class or a method final may have unintended consequences during testing. For example, when we mock classes for use in another class’s unit test, the mock is effectively a sub-class. We may be able to mitigate this issue if we are utilizing interfaces in our runtime code, rather than the concrete, final class, though.

Final Variables and Input Parameters

I intentionally left variables and input parameters out of this post. This topic is a little more of a gray area. Let’s save this for a separate post, so we can really talk through it once we have explored some more fundamentals of Java variable handling.

Summary

We aren’t going to make either of these changes in our Java101 project. However, it is important to know how a class can prevent changes in the logic of itself or its methods in any child classes.

You Shall Not Modify! Final Methods and Classes

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.