Constructors
Constructors create new instances of a class, that is objects.
Constructors are special methods that have the same name
as their class and no return type. For example,
class TwoDPoint {
double x;
double y;
TwoDPoint(double xvalue, double yvalue) {
this.x = xvalue;
this.y = yvalue;
}
String getAsString() {
return "(" + this.x + "," + this.y + ")";
}
void setX(double value) {
this.x = value;
}
void setY(double value) {
this.y = value;
}
double getX() {
return this.x;
}
double getY() {
return this.y;
}
}
}
Constructors are used along with the new
keyword to produce an object
in the class (also called an instance of the class):
TwoDPoint origin = new TwoDPoint(0.0, 0.0);
System.out.println("The x coordinate is " + origin.getX());
Previous | Next | Top
Last Modified July 25, 1998
Copyright 1997, 1998 Elliotte Rusty Harold
elharo@metalab.unc.edu