Sams Teach Yourself C in 21 Days

(singke) #1
Working with Java Classes and Methods 733

BD5


Class Constructors ........................................................................................


Every class has a special method called a constructor. Just like in C++, a class’s con-
structor is called automatically when a new instance of the class is created. You put code
in the constructor to perform any initialization steps that are required by the class. Some
simple classes do not need a constructor, so it is omitted, but most classes beyond really
simple ones will use a constructor.
The syntax for a constructor is as follows:
ClassName (ParameterList)
{
}
As you can see, the name of a constructor method is always identical to the name of the
class it is in. The ParameterListis an optional list of parameters that is passed to the
constructor. The list has the same syntax as the method arguments covered earlier today.
If the constructor takes no arguments, use a set of empty parentheses.
Listing B5.7 presents an example of a class with a constructor. The class circlehas a
property called radius, and you want to ensure that the value is always defined by set-
ting it in the constructor. Listing B5.7 shows the code for circle.java.

LISTINGB5.7 circle.java. The class circlehas a constructor
1: public class circle {
2:
3: public double radius;
4:
5: circle (double r) {
6: radius = r;
7: }
8: }

The short program in Listing B5.8 demonstrates how the constructor is used.

LISTINGB5.8 UseCircle.java. Creating a new circleobject calls the constructor
1: import java.lang.String;
2: import java.lang.Double;
3:
4: public class ConstructorDemo {
5: public static void main(String args[]) {
6:
7: circle c1;
8: c1 = new circle(1.25);

40 448201x-Bonus5 8/13/02 11:23 AM Page 733

Free download pdf