Sams Teach Yourself C in 21 Days

(singke) #1
22: System.out.println(“ The name is “ + c3.name);
23: }
24: }

For c1:
The radius is 0.0
The name is Unnamed
For c2:
The radius is 99.99
The name is Unnamed
For c3:
The radius is 0.0010
The name is Harold
In the code for the circleclass, lines 5 and 6 declare the class’s two properties.
Lines 8 to 11 define a constructor that takes no arguments, and the code here ini-
tializes the two properties to their default values. Lines 13 to 16 define a constructor that
takes a single type doubleargument, and code in this constructor initializes the radius
property to this value and the nameproperty to the default value. Lines 18 to 21 define a
third constructor, this time taking two arguments—one type doubleand one type String.
Code in this constructor uses the argument values to initialize the class’s two properties.
The demonstration program in Listing B5.10 creates three instances of the circleclass.
Lines 7 to 9 declare the variables that will hold the object references. Line 11 creates a
new instance passing no arguments, so the class’s first constructor will be called. Lines
12 and 13 create other instances of the class, passing one and two arguments respec-
tively. The remaining lines of code display the property values of the three circle
objects so you can see that the values were initialized properly.

Using Inheritance ................................................................................................


Inheritance is one of the most powerful features of Java and other object-oriented pro-
gramming languages. Inheritance lets you create a new class not from scratch, but based
on an existing class. When you do this, the new or childclass automatically has, or
inherits, all the properties and methods of the original or parentclass (sometimes called
thesuperclass). Then, you can add new properties and methods to the child class, or you
can create replacements for properties and methods from the parent class.
Let’s look at a hypothetical example. Suppose you are writing a program to perform
financial calculations. You have a class that performs just about all the needed calcula-
tions—car payments, mortgages, and so forth—but omits one thing that you want to
include in your program, lease payments. Do you need to start from scratch and create a

736 Bonus Day 5

LISTINGB5.10 continued

OUTPUT

ANALYSIS

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

Free download pdf