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 | Cafe au Lait

Copyright 1997-2006 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified September 9, 2005