Java Reference
In-Depth Information
TIP: (continued)
a method is used in a constructor and the method has no explicit calling object, the
method is understood to have this and a dot before it; that is, it is understood to
have this as its calling object.
As noted in the previous Programming Tip, the fi rst action taken by a constructor
is to automatically create an object with instance variables. This object is automati-
cally plugged in for the this parameter. So, within the defi nition of a constructor, the
this parameter refers to the object created by the constructor.
TIP: Include a No-Argument Constructor
A constructor that takes no arguments is called a no-argument constructor or
no-arg constructor . If you define a class and include absolutely no constructors
of any kind, then a no-argument constructor is automatically created. This
no-argument constructor does not do much, but it does give you an object of
the class type. So, if the definition of the class MyClass contains absolutely no
constructor definitions, then the following is legal:
no-argument
costructor
MyClass myObject = new MyClass();
If your class definition includes one or more constructors of any kind, then no
constructor is generated automatically. So, for example, suppose you define a class
called YourClass . If you include one or more constructors that each take one or
more arguments, but you do not include a no-argument constructor in your class
definition, then there is not a no-argument constructor and the following is illegal:
YourClass yourObject = new YourClass();
The problem with the above declaration is that it asks the compiler to invoke the
no-argument constructor, but there is not a no-argument constructor present.
To avoid problems, you should normally include a no-argument constructor in
any class you defi ne. If you do not want the no-argument constructor to initialize
any instance variables, you can simply give it an empty body when you implement
it. The following constructor defi nition is perfectly legal. It does nothing but create
an object (and, as we will see later in this chapter, set the instance variables equal to
default values):
public MyClass()
{/*Do nothing.*/}
(continued)
 
Search WWH ::




Custom Search