A constructor can be called by any method, since they have visibility of the constructor (The constructor can be private). There are some rules regarding the use of super(...) and this(...) Take a look at this and this
Why not invoke instance methods in a constructor? Suppose you have some specialized sub class of JDialog in a Swing GUI, and you (a) want to allow it to be constructed with both a JFrame and a JDialog as its parent (two different constructors needed), and (b) want to do the layout in the constructor (fields, listeners, etc.). Now you can copy the initialization code from one constructor to the other one, or just put it in an init() method, which you call from both constructors. What's wrong with that?
Yes, I never said that you can't but, there are many scenarios where the things may become very unsafe. The thing it has to care of is a NO leak situation. Suppose a constructor calls a instance method which may register an "instance" which may not be completely instantiated at this point of time and say anothert thread starts and then it passes control to another.... and the hell braks loose.
Until, otherwise it's fine.
Joined: Dec 22, 2004
OK, see what you mean. You have to be careful with what you're doing. But in some cases, it's the best way of avoiding duplicate code anyway. In your example of registration to some external source, why not call a respective method at the end of the constructor?
Well, the example I quoted says, Suppose you call a method and that method reserves the refrence of an external object that is not yet initialised then it would be a very bad situation.
how does calling that particular method from a constructor make this situation any more difficult..?? It is anyway a error prone situation if the external object is not yet initialized [ April 21, 2008: Message edited by: abhishek pendkay ]
The significant problems we face cannot be solved by the same level of thinking which created them – Einstein SCJP 1.5, SCWCD, SCBCD in the making