Search code examples
javaconstructorfinal

Should constructor parameters be declared final


I have seen codes where function parameters have been declared final. Surprisingly not seen code with constructor parameters declared final.

Eg:

public class Foo {

   public Foo(final int day, final int month, final int year) {
    ...
   }
}

Why is this not common ? Is there a concrete reason or just that fact that code becomes verbose ?


Solution

  • There are times when you have to declare them final:

    public class Test {
      final Runnable runner;
    
      public Test(final String text) {
        runner = new Runnable () {
          @Override
          public void run () {
            System.out.println("Run: "+text);
          }
        };
      }
    }
    

    but generally you don't have to and IMHO it is just an unnecessary distraction.