javainheritancefinalprivate-constructor

Java Final class or private constructor


When we want to close a class to inheritance we are declaring class with final,

final class Myclass {}

but when we declare the constructor private it will be the same effect,

class Myclass {
     private Myclass() {}
}

But is it really the same? Is there any difference for optimization of code or readability of code? And which classes has to close to inheritance,

  1. immutable class maybe
  2. every method and member variable declared static of class

But for second option java.util.Arrays hasn't been declared with final even if all methods of Arrays are declared static.


Solution

  • but when we declare ctor private it will be the same effect

    Not necessarily, consider this example using static classes:

    public class SOExample {
        private static class ClassWithPrivateConstructor {
            private ClassWithPrivateConstructor() {
                System.out.println("I have a private constructor");
            }
        }
    
        private static class ClassThatExtendsClassWithPrivateConstructor extends ClassWithPrivateConstructor {
        }
    
        public static void main(String[] args) {
            new ClassThatExtendsClassWithPrivateConstructor();
        }
    }
    

    This will print "I have a private constructor".

    but is it really same? is there any difference for optimization of code or readablity of code. and which classes has to close to inheritance,

    When a developer sees that a class is final, they understand that the intention of the author was that it should not be extended.

    When a developer sees that a class has a private constructor, they understand that the class can't be instantiated. This is generally because it is either a static utility class or a singleton.

    But for second option java.util.Arrays hasn't declared with final even if all methods of Arrays declared static

    This is a good observation. My guess is that it probably should have been but can't be changed now for backward compatibility.