7.3. Constructors

 
[Page 216 ( continued )]

The constructor has exactly the same name as the defining class. Like regular methods , constructors can be overloaded (i.e., multiple constructors with the same name but different signatures), making it easy to construct objects with different initial data values.

To construct an object from a class, invoke a constructor of the class using the new operator, as follows :

   new   ClassName(arguments); 

For example, new Circle() creates an object of the Circle class using the first constructor defined in the Circle class, and new Circle(5) creates an object using the second constructor defined in the Circle class.

A class normally provides a constructor without arguments (e.g., Circle() ). Such a constructor is called a no-arg or no-argument constructor .

A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor , is provided automatically only if no constructors are explicitly declared in the class .

Note

Constructors are a special kind of method, with three differences:

  • Constructors must have the same name as the class itself.

  • Constructors do not have a return type ”not even void .

  • Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.


Caution

It is a common mistake to put the void keyword in front of a constructor. For example,

   public    void  Circle() { } 

In this case, Circle() is a method, not a constructor.


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net