Java Reference
In-Depth Information
System.out.println("\nSecond object:");
nextexample.listValues();
example.listValues();
}
While you have demonstrated that this is possible, you do not normally want to initialize static variables
with a non-static initialization block.
As I said at the outset, a non-static initialization block can initialize instance variables, too. If you want
to demonstrate this, you just need to remove the static modifier from the declaration of values and
compile and run the program once more.
You can have multiple initialization blocks in a class, in which case they execute in the sequence in which
they appear. The static blocks execute when the class is loaded, and the non-static blocks execute when
each object is created. Initialization blocks are useful, but you need more than that to create objects prop-
erly.
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 supplies 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 cre-
ating 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 theRadius, double x, double y, double z) {
radius = theRadius;
// Set the radius
Search WWH ::




Custom Search