Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces


The Class Body

Earlier you saw the general outline of a class implementation:
classDeclaration {
    classBody
}
The The Class Declaration(in the Writing Java Programs trail) described all of the components of the class declaration. This page describes the general structure and organization of the class body.

The class body component of a class implementation can itself contain two different sections: variable declarations and methods. A class's member variables represent a class's state and its methods implement the class's behavior. Within the class body you define all the member variables and methods supported by your class.

Typically, you declare a class's member variables first and then you provide the method declarations and implementations, although this is not required.

classDeclaration {
    memberVariableDeclarations
    methodDeclarations
}
Here's a small class that declares three member variables and a method:
class TicketOuttaHere {
    Float price;
    String destination;
    Date departureDate;
    void signMeUp(Float forPrice, String forDest, Date forDate) {
        price = forPrice;
        destination = forDest;
        departureDate = forDate;
    }
}
For more information about how to declare member variables, see Declaring Member Variables. And for more information about how to implement methods, see Implementing Methods.

In addition to the member variables and methods you explicitly declare within the class body, your class may also inherit some from its superclass. For example, every class in the Java environment is a descendent (direct or indirect) of the Object class, that is, every class in Java inherits variables and methods from Object. The Object class defines the basic state and behavior that all objects must have such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and so on. Thus, as descendents of this class, all objects in the Java environment inherit this behavior from the the Object class.

Subclasses, Superclasses, and Inheritance contains more information about inheritance. The Object Class talks about the features of the Object class.


Previous | Next | Trail Map | Writing Java Programs | Objects, Classes, and Interfaces