spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / java / beginning / chap5 / 2 current pageTo page 2To page 3To page 4To page 5To page 6
[next]

Beginning Java 2 SDK 1.4 Edition

UNIX System Administrator - SUN Solaris, Veritas, EMC, Shell Scripting, SAN (NYC)
Next Step Systems
US-NY-New York

Justtechjobs.com Post A Job | Post A Resume
Developer News
ActiveState Debuts Open Source Business Suite
Salesforce Offers Visual App Builder
Codesion Steps Out From CVS's Shadow


Constructors

[The following is a continuation of our series of excerpts from chapter 5 of the Wrox Press title, Beginning Java 2 SDK 1.4 Edition. Source code for the examples discussed can be downloaded at the Wrox Web site (free e-mail registration required).]

When you create an object of a class, a special kind of method called a constructor is always invoked. If you don't define any constructors for your class, the compiler will supply a default constructor in the class that does nothing. The primary purpose of a constructor is to provide you with the means of initializing the instance variables uniquely for the object that is being created. If you are creating a Person object with the name John Doe, then you want to be able to initialize the member holding the person's name to "John Doe". This is precisely what a constructor can do. Any initialization blocks that you have defined in a class are always executed before a constructor.

A constructor has two special characteristics that differentiate it from other class methods:

  • A constructor never returns a value and you must not specify a return type--not even of type void.

  • A constructor always has the same name as the class.

To see a practical example we could add a constructor to our Sphere class definition:

class Sphere {
  static final double PI = 3.14; // Class variable that has a fixed value
  static int count = 0;          // Class variable to count objects

  // Instance variables
  double radius;                 // Radius of a sphere

  double xCenter;                // 3D coordinates
  double yCenter;                // of the center
  double zCenter;                // of a sphere
 
  // Class constructor
  Sphere(double theRadius, double x, double y, double z) {
    radius = theRadius;         // Set the radius

    // Set the coordinates of the center
    xCenter = x;
    yCenter = y;
    zCenter = z;
    ++count;                    // Update object count
  }

  // Static method to report the number of objects created
  static int getCount() {
    return count;               // Return current object count
  }

  // Instance method to calculate volume
  double volume() {
    return 4.0/3.0*PI*radius*radius*radius;
  }
}

The definition of the constructor is shaded above. We are accumulating quite a lot of code to define the Sphere class, but as it's just an assembly of the pieces we have been adding, you should find it all quite straightforward.

As you can see, the constructor has the same name as the class and has no return type specified. A constructor can have any number of parameters, including none. The default constructor has no parameters. In our case we have four parameters, and each of the instance variables is initialized with the value of the appropriate parameter. Here is a situation where we might have used the name radius for the parameter, in which case we would need to use the keyword this to refer to the instance variable of the same name. The last action of our constructor is to increment the class variable, count, by 1, so that count accumulates the total number of objects created.

The Default Constructor

If you don't define any constructors for a class, the compiler will supply a default constructor that has no parameters and does nothing. Before we defined a constructor for our Sphere class, the compiler would have supplied one defined like this:

Sphere() {
}

It has no parameters and has no statements in its body so it does nothing--except enable you to create an object of type Sphere of course. The object created by the default constructor will have fields with their default values set.

Note that if you define a constructor of any kind for a class, the compiler will not supply a default constructor. If you need one--and there are occasions when you do--you must define it explicitly.


home / programming / java / beginning / chap5 / 2 current pageTo page 2To page 3To page 4To page 5To page 6
[next]


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Use Web Caching to Make Your Web Site Faster · Creating an Online Shopping Cart Mechanism in PHP · Log JavaScript Errors Using an AJAX-driven Web Service
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Configuring Granular Settings for a Database Level Audit · The Perils of a Web 2.0 Transition on Your Business Processes · Facebook Redesigns Site —Again — Nears 400M Mark

Created: July 1, 2002
Revised: July 1, 2002


URL: http://webreference.com/programming/java/beginning/chap5/2/