-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Closed
Description
$ cat Test.java
public class Test {
public static final Test ONE = new Test() {
@Override
public int value() {
return 1;
}
};
private Test() {
}
public int value() {
return 0;
}
}
$ cat config.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<module name="TreeWalker">
<module name="FinalClass"/>
</module>
</module>
$ RUN_LOCALE="-Duser.language=en -Duser.country=US"
$ java $RUN_LOCALE -jar checkstyle-8.41-all.jar -c config.xml Test.java
Starting audit...
[ERROR] /Users/archie/bugs/checkstyle-A/Test.java:1:1: Class Test should be declared as final. [FinalClass]
Audit done.
Checkstyle ends with 1 errors.
The FinalClass
module is doing it's job correctly in that it's detecting a non-final class with only private constructor(s), but it's not smart enough to realize that in some situations - e.g., this particular situation where you are defining nested classes within the outer class - it's not possible to make the class final
because otherwise those nested classes would be impossible to write, because the compile would fail because you can't extend a final class.
Java allows nested classes to extend a class using a private superclass constructor. So the upshot is that FinalClass
should make an exception when the class being checked contains any nested subclasses.