Sams Teach Yourself C in 21 Days

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

BD5


The optional extendssuperClassNameclause is used when you are using inheritance—
in other words, when the new class is based on an existing class. The class you are inher-
iting from can be a class you created or a class that is part of Java, as long as the class
was not created using the finalkeyword. When you create a class based on a superclass,
the new class automatically inherits all the superclass’s methods and properties.
Inheritance will be covered in more detail later today.

A class, like a Java program, requires that you include all the classes and
packages utilized by the code in that class. The includestatements come
just before the class definition in the source code file.

Caution


Specifying the Class Package ........................................................................

Every class that you create in Java is part of a package. To specify which package, use
thepackagekeyword in your class definition file. This statement should be the very first
one in the file, before any includestatements:
package PackageName;
If you omit a package specification, the class will be put in a default, no-name package.
This is not a good idea. You should create packages containing related classes, which
will help you keep track of things. Then, when another source code file needs the class,
you can use the importstatement to import the entire package or one or more specific
classes from the package.

Creating Class Properties ..............................................................................

Apropertyis a chunk of data, or information, associated with a class. For example, if
you created a class called Circleto represent a circle, it would probably have a property
calledRadiusfor the circle’s radius. A property of a class is nothing more than a variable
declared inside the class and made available outside the class. You learned the basics of
Java variables and how to declare them on Bonus Day 4. A variable that is to serve as a
property must be declared at the start of the class definition, outside any methods:
public class circle
{
public double radius;
public int anotherProperty;
public byte yetAnotherProperty;
public MyClass anObjectProperty; // MyClass is a programmer-defined class.
public String oneLastProperty;
// Other class code goes here.
}

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

Free download pdf