Java-Final class vs private constructor: Difference between java.util.Arrays and java.lang.Math

Antonio1996 :

I know the difference between a final class (you can't inherit the class) and a private constructor (you can't create an instance of the class). But why Arrays and Math, classes of Java, have both private constructors but Math is final class and Arrays is not?

What is the difference? Are not both utility classes?

Thanks

M. Prokhorov :

When class has a private constructor but is not final, you can define inner classes in the same class file that have public constructors and can be instantiated. But you cannot define any subclasses outside of that initial class file. For example this would compile:

public class Animal {
  public void say() {
    System.out.printLn("Animal says:");
  }
  private Animal() {}

  public static class Cat extends Animal {
    public Cat() {super();}
    @Override public void say() {
      super.say();
      System.out.printLn("Meow");
    }
  }
}

However, this (defined in another file) will not:

public class Dog extends Animal {
  public Dog() {super();} // compilation error here: The constructor Animal() is not visible
  @Override public void say() {
    super.say();
    System.out.printLn("Wuf");
  }
}

This technique allows you to define class hierarchy where you have full control over what types can extend your class (because all these subtypes have to be enumerated inside of same class file).

That said, java.util.Arrays is not defined as non-final because of the above - it is probably just an implementor's oversight that does not matter all that match, so it was not fixed to date.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=453199&siteId=1