hudebnik: (Default)
hudebnik ([personal profile] hudebnik) wrote2012-12-19 07:13 am

Java annoyances

Java's constructors have annoyed me for years. They're called and defined with a different syntax from any other method, and they can't be inherited. If objects of a bunch of classes are each supposed to be able to create duplicates or near-duplicates of themselves, each such method has to be written separately, no matter how similar they are, because they all call different constructors. And Java constructors always produce a new instance of the specified class -- they can't return an existing instance, they can't return an instance of a subclass of this one, and they certainly can't return an instance of another class that implements the same interface. All of which means they're heavily tied to implementation, and should not be exposed in an API.

One can get around some of this by using pseudo-constructors, aka factory methods. If the whole purpose of a factory method is to return a (possibly) new object, one must be able to call the method without already having an object of the class, so it has to be static. Unfortunately, static methods can't be abstract, so they can't be specified in an interface; if a dozen classes all have static methods with the exact same signature, you still have to specify them all separately.