Sams Teach Yourself C in 21 Days

(singke) #1
there are additional details to the class definition. The following is the most basic syntax
for a class definition:
class className
{

}
That’s pretty simple. In fact, it looks exactly like a program class definition (there gener-
ally will be no main()method, however). The classkeyword is required to identify a
class definition. The classNameis an identifier for the class created using the Java identi-
fier rules described on Bonus Day 4. This is the name you’ll use to refer to the class in
your programs.
Few class definitions are so simple, however, so there will usually be additional elements
in the definition. The full syntax for a class definition, with optional elements in brack-
ets, is
[modifiers] class className[extends SuperClassName]
{
}
The modifiers control two things about the class. One is its privacy, which determines
the scope of the class (you learned about scope on Bonus Day 4). Privacy keywords for
class definitions are listed in Table B5.1. Most classes you create will be public.

TABLEB5.1 Privacy keywords for class definitions
Keyword Description
public Class accessible to everyone
private Class accessible to no one
[no keyword] Class accessible throughout its package
protected Class accessible throughout its package and within subclasses

The second thing controlled by the modifiers has to do with inheritance. You can use one
(but not both) of the following keywords:


  • Abstract. You can inherit from this class (use it as a superclass), but you cannot
    create instances of the class. Use abstractwhen you create a class that is
    designed as a template for other classes, but you cannot use it on its own.

  • Final. You can create instances of the class, but it cannot be used as a superclass
    (another class cannot inherit from this class).


724 Bonus Day 5

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

Free download pdf