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


Creating Classes

Now that you know how to create, use, and destroy objects, it's time to learn how to write the classes from which objects can be created.

A class is a blueprint or prototype that you can use to create many objects. The implementation of a class is comprised of two components: the class declaration and the class body.

classDeclaration {
    classBody
}

The Class Declaration

The class declaration component declares the name of the class along with other attributes such as the class's superclass, and whether the class is public, final, or abstract.

The Class Body

The class body follows the class declaration and is embedded within curly braces { and }. The class body contains declarations for all instance variables and class variables (known collectively as member variables) for the class. In addition, the class body contains declarations and implementations for all instance methods and class methods (known collectively as methods) for the class.

Declaring Member Variables

A class's state is represented by its member variables. You declare a class's member variables in the body of the class. Typically, you declare a class's variables before you declare its methods, although this is not required.
classDeclaration {
    member variable declarations
    method declarations
}
Note: To declare variables that are members of a class, the declarations must be within the class body, but not within the body of a method. Variables declared within the body of a method are local to that method.

Implementing Methods

As you know, objects have behavior that is implemented by its methods. Other objects can ask an object to do something by invoking its methods. This section tells you everything you need to know about writing methods for your Java classes. For more information about how to call methods see Using Objects.

In Java, you define a class's methods in the body of the class for which the method implements some behavior. Typically, you declare a class's methods after its variables in the class body although this is not required.

Controlling Access to Members of a Class

Member variables and methods are known collectively as members. When you declare a member of a Java class, you can allow or disallow other objects of other types access to that member through the use of access specifiers.

Instance and Class Members

A Java class can contain two different types of members: instance members and class members. This page shows you how to declare both types of members and how to use them.

Life Cycle Methods

You can declare two life cycle methods within the body of your class: constructors and the finalize method. For more information follow the links provided below:


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