5.4. Constructors

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, which does nothing. The default constructor is also described as the no-arg constructor because it requires no arguments to be specified when it is called. 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 you could add a constructor to the 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 ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.