Constructors, sometimes abbreviate to ctor by habitual text-speakers, are a special sort of method that initialise freshly minted objects. They are like static methods in that you don’t need an existing object to use them, just new. They are like instance methods in that they operate on the current object. They are a bit like static factory methods in that they are used in creating new objects, however, they don’t create objects, just initialise them. I repeat, they don’t allocate objects, they just initialise them. new allocates the space for objects.
| Constructors Are Not Ordinary Methods | factory |
| Object Initialisation | Links |
| addNotify |
Don’t put GUI-type code in your constructor. Put it in an addNotify method that looks like this:
/** * Build the GUI */ public void addNotify() { super.addNotify(); setTitle( "Whazmotron Inc." ); ... }
Don’t forget to call super.addNotify () ; first, or the peer object won’t get created and your Component won’t be hooked into the actual underlying native GUI (Graphic User Interface) and you will be staring at a blank screen.
Putting GUI code here means the GUI is ready for it. The peer exists as soon at the code returns from the call to super.addNotify(), not before. the peer does not yet exist in the constructor. You need a peer for getImage type activities. Further, if you call methods in your constructor that subclasses override, it means you are less likely to be referencing variables that don’t exist yet if you divide your initialisation logically between the constructor and addNotify.
This is also a good place to move constructor code that is failing because it uses methods overridden my subclasses that reference fields not yet initialised by the subclass’s constructor which has not yet run yet.
|
|
available on the web at: |
http://mindprod.com/jgloss/constructor.html |
optional Replicator mirror
|
J:\mindprod\jgloss\constructor.html | |
![]() |
Please email your
feedback for publication,
letters to the editor, errors, omissions, typos, formatting errors, ambiguities, unclear
wording, broken/redirected link reports, suggestions to improve this page or comments to
Roedy Green :
| |
| Blog | Canadian
Mind
Products
IP:[65.110.21.43] Your face IP:[23.20.196.179] |
|
| Feedback | You are visitor number 94,622. | |