Reputation: 15942
I'm a die-hard C++ fan who is picking up Java for Android apps. In C++, the canonical way of creating and initializing an object would be to totally intialize it in the constructor:
class Message {
string payload;
int client;
// etc.
public:
Message(string payload, int client)
: payload(payload)
, client(client)
{}
};
This seems possible to do in Java. It gets a bit uglier because I want to make certain members const
(the best Java can do is final
), but generally I can figure it out.
But now I'm running across libraries such as FreeHEP-XDR
, whose XDRSerializable
interface specifies a signature:
void read(XDRDataInput in);
This function, which will be implemented by Message
, is obviously not a static instantiator, as it returns void
. The Message
object would have to be fully constructed, probably with a default constructor, before calling this function. This bothers me: the caller can easily pass an XDRDataInput
in the constructor, and anyway I'll be initializing the object twice (once in the default constructor, again in read
). Most egregiously, implementing this requires me to drop my final
modifier from certain Message
data members, because they'll be modified after the constructor is finished!
Is this par for the course for Java? What's the object protection, creation, and initialization paradigm?
Upvotes: 4
Views: 134
Reputation: 1858
Well, the main issue with constructors is that they are not polymorphic. Meaning that the client whose invoking such constructors needs to always know what concrete type is she building. By deferring initialization and construction you can, pontentially, take the decision of which concrete instance you want to create at point a and polimorfically initialize it at point b.
Also, java does not have any way to force implementors of a certain contract (an interface, by example) to define a certain constructor. So it is either adding a weak condition to the interface contract (like a comment in the javadoc saying that implementors should provide a constructor that receives XHRDataInput) or adding a initialization method to the interface and forcing you to provide an empty constructor instead (which is by far a more common practice, probably inherited from the JavaBeans "specification").
Having said that I will also state: Yes it totally breaks your "final" semantics. You can add a check in your "read" method that checks over a certain condition and ensure that your object is initialized only once (throwing an Exception if read is invoked twice), but that is totally up to you.
Upvotes: 2