Java Reference
In-Depth Information
When we relied on the default constructor supplied by the compiler, we had to write
code like this to initialize the radius explicitly:
Circle c = new Circle ();
c . r = 0.25 ;
With the new constructor, the initialization becomes part of the object creation step:
Circle c = new Circle ( 0.25 );
Here are some basic facts regarding naming, declaring, and writing constructors:
• The constructor name is always the same as the class name.
• A constructor is declared without a return type, not even void .
• The body of a constructor is initializing the object. You can think of this as set‐
ting up the contents of the this reference
• A constructor may not return this or any other value.
Deining Multiple Constructors
Sometimes you want to initialize an object in a number of different ways, depending
on what is most convenient in a particular circumstance. For example, we might
want to initialize the radius of a circle to a specified value or a reasonable default
value. Here's how we can define two constructors for Circle :
public Circle () { r = 1.0 ; }
public Circle ( double r ) { this . r = r ; }
Because our Circle class has only a single instance field, we can't initialize it too
many ways, of course. But in more complex classes, it is often convenient to define a
variety of constructors.
It is perfectly legal to define multiple constructors for a class, as long as each con‐
structor has a different parameter list. The compiler determines which constructor
you wish to use based on the number and type of arguments you supply. This ability
to define multiple constructors is analogous to method overloading.
Invoking One Constructor from Another
A specialized use of the this keyword arises when a class has multiple constructors;
it can be used from a constructor to invoke one of the other constructors of the
same class. In other words, we can rewrite the two previous Circle constructors as
// This is the basic constructor: initialize the radius
public Circle ( double r ) { this . r = r ; }
// This constructor uses this() to invoke the constructor above
public Circle () { this ( 1.0 ); }
Search WWH ::

Custom Search