Java Reference
In-Depth Information
TryInitialization nextexample = new TryInitialization();
System.out.println("\nSecond object:");
nextexample.listValues();
example.listValues();
}
While we have demonstrated that this is possible, you will not normally want to initialize static variables
with a non-static initialization block.
As we said at the outset, a non-static initialization block can initialize instance variables too. If you want
to demonstrate this too, 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 properly.
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 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
Search WWH ::




Custom Search