Java Reference
In-Depth Information
public class ErrorMsg {
public static int total_counter;
// A constructor definition for this class. Note that all constructors
// have the same name as the class. This constructor has no parameters:
ErrorMsg () {
total_counter = -1;
}
// A regular class instance method with no parameters:
public static void resetErrorMsgCount () {
total_counter = 0;
}
As in regular method definitions, a class can have more than one constructor de-
finition. They are identified by their signature, or number and types of parameters.
public class ErrorMsg {
public static int total_counter;
// A constructor for this class. Note that this constructor has no
// parameters:
ErrorMsg () {
total_counter = -1;
}
// A constructor for this class that is passed one parameter.
ErrorMsg (String initialMsgText) {
total_counter = -1;
msgText = initialMsgText;
}
The consumer class does not explicitly call the constructor method. Instead, the
new operation implicitly calls it. The class consumer identifies which constructor to
call by adding parameters to the new operation.
// Create an instance of ErrorMsg.
// The constructor with no parameters will be called.
ErrorMsg myErrorMsg = new ErrorMsg ();
// Create another instance of ErrorMsg.
// The constructor with one parameters will be called.
ErrorMsg myotherErrorMsg = new ErrorMsg ("Some Text");
A constructor can execute some other constructor in the current class. This is
useful if a class has more than one constructor definition but would like to share
some code between them. The this keyword is used as an object reference variable
that points to the current object.
Search WWH ::




Custom Search