|
Previous Next
Constructor Method
A constructor is a method used to initialize the attributes of the object at the time the object is created. It may also do other processing that needs to be done at creation time. It has the same name as the class where it is found. One class can have multiple constructors if we want to use a different list of and type of parameters at different times.
In this example, we have the class called Dog. Dog has 3 data elements, color, size, and hairlength. The constructor, also called Dog, accepts 3 parameters, xcolor, xsize, and xhairlength. These 3 parameters in the constructor set the values in the class for the particular object.
class Dog {
String color;
int size;
String hairlength;
Dog(String xcolor, int xsize, String xhairlength) {
color = xcolor;
size = xsize;
hairlength = xhairlength;
}
public static void main(String args[]) {
Dog Spot = new Dog("BlackAndWhite", 60, "short");
Dog Lassie = new Dog("Brown", 80, "long");
System.out.println("Spot's color is " + Spot.color
+ " and Lassie's weight is " + Lassie.size);
}
}
Here we have the 2 objects, Spot and Lassie with different characteristics even though they are both instantiated from the same class Dog. The following statements both create the objects, Spot and Lassie, and call the constructor Dog of the class Dog. Different values are passed to each constructor which makes Spot different from Lassie.
Dog Spot = new Dog("BlackAndWhite", 60, "short");
Dog Lassie = new Dog("Brown", 80, "long");
Putting this code into Dog.java and testing it should yield:
Previous Next
|