Monday, August 20, 2007

What is constructor?

Every class has at least one constructor, a method which has the same name as the class. A constructor initializes a new object belonging to the class. public class Particle
{
double x, y, vx, vy, mass; // these variables can be used by any method in the class
// example of constructor method
public Particle(double x, double y, double vx, double vy, double mass)
{
/* Use this keyword to make explicit that a method
is accessing its own variables. */
this.x = x; // set instance variable x equal to value of x in parameter list
this.y = y;
this.vx = vx;
this.vy = vy;
this.mass = mass;
}
}
The constructor Particle creates an object of the Particle class by specifying five parameters: the initial position and velocity of a particle and the value of its mass. We say that Particle is the constructor for the Particle class.

No comments: