Java Reference
In-Depth Information
variables. In fact, only static class variables can be accessed by the initializer code.
There are no instance member variables available to this code, since class initializer
code is performed only once and before any instances of the class have been created.
public class ErrorMsg {
// Public instance variables:
public String msgText;
public int msgSize;
// A public class variable
public static int TOTAL_COUNTER;
// A class initializer code block
static void TOTAL_COUNTER (){
TOTAL_COUNTER = 1;
}
// A regular instance method
public void setErrorMsg (String inputMsg) {
...
...
}
}
C ONSTRUCTORS
Now is a good time to talk about constructors. When an object is first instantiated
(with the new operator), the JVM will create the new instance of the class and call its
constructor . This is a special built-in definition that performs any initialization logic
that may be required by that class. Constructors are not methods, but they are sim-
ilar to methods in some respects. This special, perform-one-time-only definition
exists in every object, even if the class designer didn't explicitly define it.
As with real methods, a class can have more than one constructor; each one is
identified by a unique parameter signature. By default, every class will have at least
one constructor, a constructor that accepts no parameters. This default constructor
will be generated by the compiler if the class has no constructors defined for it.
Sometimes the default constructor is called the “no arguments” constructor.
These constructors are useful for any number of reasons, such as initializing an
important member of the object. The programmer defines a constructor by declar-
ing a special definition in the class. This definition must have exactly the same name
as the class and have no return type.
Search WWH ::




Custom Search