FinalClass

Since Checkstyle 3.1

Description

Ensures that identifies classes that can be effectively declared as final are explicitly marked as final. The following are different types of classes that can be identified:
  1. Private classes with no declared constructors.
  2. Classes with any modifier, and contains only private constructors.

Classes are skipped if:

  1. Class is Super class of some Anonymous inner class.
  2. Class is extended by another class in the same file.

Examples

To configure the check:

<module name="Checker">
  <module name="TreeWalker">
    <module name="FinalClass"/>
  </module>
</module>
        

Example:

public class Example1 { // ok, since it has a public constructor

  final class A {
    private A() {
    }
  }

  class B { // violation, 'Class B should be declared as final.'
    private B() {
    }
  }

  class C { // ok, since it has a public constructor
    int field1;
    String field2;

    private C(int value) {
      this.field1 = value;
      this.field2 = " ";
    }

    public C(String value) {
      this.field2 = value;
      this.field1 = 0;
    }
  }

  class AnonymousInner { // ok, class has an anonymous inner class.
    public final AnonymousInner ONE
            = new AnonymousInner() {
            };

    private AnonymousInner() {
    }
  }

  class Class1 {

    private class Class2 { // violation, 'Class Class2 should be declared as final'
    }

    public class Class3 {
    }

  }
}
        

Example of Usage

Violation Messages

All messages can be customized if the default message doesn't suit you. Please see the documentation to learn how to.

Package

com.puppycrawl.tools.checkstyle.checks.design

Parent Module

TreeWalker