Java Reference
In-Depth Information
TIP: (continued)
ever 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 first 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 definition 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
constructor
MyClass myObject = new MyClass();
If your class definition includes one or more constructors of any kind, then no con-
structor 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 argu-
ments, 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 no no-argument constructor in this case.
To avoid problems, you should normally include a no-argument constructor in any
class you define. 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 definition 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.*/}
Search WWH ::




Custom Search