O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required