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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access