Java Classes - Creating Objects with Constructors (
Page 5 of 5 )
Classes contain constructors, which are used to create objects based off of that class' blueprints. The declaration of a constructor is similar to that of a method, with the exception that they use the same name as the class and have no return type. Here is an example of the BruceLee constructor:
public BruceLee(int doKick, int doPunch, int doRoundhouse) {
punch = doPunch;
kick = doKick;
roundhouse = doRoundhouse;
}
If we wanted to create a new BruceLee object and name it myPupil, we could use the new operator to do so:
BruceLee myPupil = new BruceLee(10, 5, 2);
Now a new object name myPupil has been created, and its punch, kick, and roundhouse have all been assigned the values 10, 5, and 2, respectively.
Well that's all the time we have for this article. In our next part, we will learn to pass information to a Method or constructor, and work more with Objects.
Till then...