Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com

The point.

First click, a TextField is constructed this way.

Next one, constructed in a different manner.

The third one is also constructed differently.

And the last one.

If we look inside the (simplified) source file for TextField, we find four different constructors.

First click, this one's executed,....

corresponding exactly to this call.

Next construction, this one ,...

called by.

Third one ....

...called

Last,....

...called.

As you've seen, all constructors in a class must have the name of the class.

The compiler deduces which constructor must be called from the number and type of parameters.

You can use this technique in an own class to be able to construct instances in different ways :


OCPerson pers = new OCPerson ( "Nikolos", 25 ) ;


OCPerson pers = new OCPerson ( "Spyduhrmahn" ) ;
===========

Constructors are meant for initializing,...

- mostly copying parameters.....

.... to instance variables, ....

but you can also think of :

- creating arrays

- creating instances of other classes you're going to use

- reading resources : data, images, sound .

- connecting to a database ...etc.

! ! ! FOR AN APPLET this is DIFFERENT. ONLY WHEN the INIT METHOD is STARTED it can do all it can do, because the init method is called after its construction has been completed. Only then is it ready to function fully within the browser context.

You can do simple things in an applet's constructor, however, as we do in many of our examples, like creating instances of simple visual components, creating arrays, things like that, to improve readability and adhere to the convention of constructing in the constructor.

======

The following is NOT a constructor :
public void OCPerson ( String nm )
{ ..... }

because of the word void.

The compiler will approve of it, but it won't be called.

======

You're not obligated to have constructors in your code, so, if you don't have any, a constructor without parameters is generated, and is therefore called a DEFAULT CONSTRUCTOR.

If you do decide to have constructors, you should provide this one, too, even if it seems, that there's no use for a constructor without parameters.

======

You can call another constructor from a constructor, so instead of this,.....

you could code :
this ( lnm, -1 ) ;

resulting in a call to this constructor.

.