Java Reference
In-Depth Information
3. All boolean variables are set to false
Aunique characteristic of constructors is that they have no return
type. Constructors can be public, private, or protected, but most con-
structors are public. Aprivate constructor does not allow other classes to
instantiate objects. Therefore, a class with a private constructor can only
have static methods.
Programmers note:
Youuseaprivateconstructorwhenyouwanttopreventotherclasses
from instantiating your class, but you still need access to the class'
static methods.
The default constructor
Theconstructoriscalledwhenanobjectoftheclassiscreated.Forexam-
ple,inthecaseoftheVirtualDog.javaprogramlistedpreviously,the default
constructor iscalledwhentheobjectsarecreated,asinthefollowingstate-
ment:
// Declare objects of class Dog
Dog myDog = new Dog();
// First object is named myDog
The default constructor creates the object and sets the field variables
that were not initialized in their declaration to the default values men-
tioned previously. In the case of the sample program named
VirtualDog.java, listed earlier, the default constructor sets the variable
dogNum to zero, and the String dogName to null.
Overloading the constructor
In general, the word overloading refers to using a program element for
more than one purpose. For example, the Java + operator is overloaded
sinceitisusedtorepresentboth additionandconcatenation.WhenaJava
class contains more than one constructor we say that the constructor is
overloaded.
Overloaded constructors must follow the rule that each implementa-
tion of the constructor have a unique signature.
Search WWH ::




Custom Search