Sams Teach Yourself C in 21 Days

(singke) #1
9: System.out.println(“The circle’s radius is “
10: + Double.toString(c1.radius));
11: }
12: }

The circle’s radius is 1.25
The first listing defines a class named circle. Line 1 is the class definition, and
line 3 declares a property named radius. The constructor is in lines 5 to 7. You
can see that the constructor is declared to take one type doubleargument. When the con-
structor is called, the value passed in the argument ris assigned to the property radius.
The second listing shows how the constructor is used. Lines 1 to 5 should be familiar to
you. Line 7 declares a variable of type circle. Line 8 uses the newkeyword to create an
instance of the class circle. When the instance is created, the constructor is called and is
passed the argument 1.25that is specified. Lines 9 and 10 demonstrates that the value is
indeed stored in the radiusproperty by displaying it on the screen.
Java is very careful about matching the arguments passed to a constructor and the para-
meters declared as part of the constructor. If they do not match in number and type, the
program will not compile. If a class has no constructor at all or has a constructor defined
with no parameters, use empty parentheses when creating an instance of the class:
MyObject = new ClassName();
Like any method, a class constructor can be overloaded. This can be useful when there
are different ways of initializing the object. Remember, overloaded methods have the
same name, but you can identify them by their parameters. To demonstrate, modify the
previous example so that the circleclass has another property,name, used to hold a text
description of the object. You’ll add two more constructors to the class to permit three
ways of initializing it:


  • Pass no arguments. Radiusis set to 0 , andnameis set to “Unnamed”.

  • Pass one numeric argument. Radius is set to the argument value, and name is set to
    “Unnamed”.

  • Pass one numeric and one string argument. Both radiusandnameare initialized.
    Listings B5.9 and B5.10 show the source code for the new class and demonstration pro-
    gram.


734 Bonus Day 5

LISTINGB5.8 continued

OUTPUT

ANALYSIS

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

Free download pdf