What you are describing is probably called a factory method. There is a Wikipedia page about that, but they chose to instantiate complex numbers, which are not easy to read. There is an easier example to understand in Joshua Bloch’s book Effective Java™, pages 5-16. I recommend you read that, if you can find a copy.
We do not usually hand out code, but this is the sort of thing which would be unfamiliar to you, so it is appropriate here. The following class is written in such a way as to be immutable, and has a private constructor, so the only way you can get instances is via the factory method. Because of this, there are all sorts of other fiddles you can work, including caching instances.Bloch says that names for factory methods include getInstance, newInstance, valueOf, of, getType and newType. In most cases, they must be invoked before an instance of the class is created, so they are marked static.
does it mean we can construct multiple objects with specific attributes(constructor) in one class? sorry if this is another stupid question but i want to know do i really have to make that much classes just to make multiple objects?
Joined: Oct 13, 2005
If you mean, “can we use such a method several times to create several objects with different attributes?”, then, yes. And yes, you can use such methods to call different constructors, but it is probably easier to use overloaded methods to call overloaded constructors.
You don’t have to use factory methods; this can all be done with direct constructor calls.
Find the Effective Java™ section I mentioned earlier. It explains this question far better than I can.
A class can have multiple constructors. It can also have no explicit constructors, in which case the Java compiler will provide a default no-argument constructor. It is up to the programmer/designer to decide how many constructors are appropriate for a class.
You normally create objects by using the new keyword followed by an appropriate constructor. For example, new Student() will create (allocate memory) and initialize a new instance (object) of the Student class.
You don''t have to keep apologizing about your questions. We try to be very understanding here and give newbies a pretty hefty allowance of "stupid" questions. BTW, there is no such thing as a "stupid" question, as long as you ShowSomeEffort (<-- click on link).
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com