Making Your Own Classes
Okay, class, it's time to learn how to create your own classes.
In this chapter, you discover the basics of creating classes in Java. All Java programs are classes, so you've already seen many examples of classes. For example, you've seen class headers such as public class GuessingGame and static methods such as public static void main. Now, in this chapter, I show you how to create programs that have more than one class.
Declaring a Class
All classes must be defined by a class declaration-lines of code that provide the name for the class and the body of the class. Here's the most basic form of a class declaration:
[public] class ClassName { class-body }
The public keyword indicates that this class is available for use by other classes. Although it is optional, you usually include it on your class declarations. After all, the main reason you write class declarations is so other classes can create objects from the class you're defining. (Find out more about using the public keyword in the section "Where classes go" later in this chapter.)
TECHNICAL STAUFF | In later chapters of this book, you find out about some additional elements that can go in a class declaration. The format I'm describing here is just the basic format used to create basic classes. |
Picking class names
The ClassName is an identifier that provides a name for your class. You can use any identifier you want to name a class, but the following three guidelines can simplify your life:
-
Begin the class name with a capital letter. If the class name consists of more than one word, capitalize each word. For example, Ball, RetailCustomer, and GuessingGame.
-
Whenever possible, use nouns for your class names. Classes create objects, and nouns are the words you use to identify objects. Thus most class names should be nouns.
-
Avoid using the name of a Java API class. No rule says you absolutely have to, but if you create a class that has the same name as a Java API class, you have to use fully qualified names (such as java.util. Scanner) to tell your class apart from the API class with the same name.
Tip There are literally thousands of Java API classes, so avoiding them all is pretty hard. But at the least, you should avoid commonly used Java class names-as well as any API classes your application is likely to use. For example, creating a class named String or Math is just asking for trouble.
What goes in the class body
The class body of a class is everything that goes within the braces at the end of the class declaration. The public class ClassName part of a class declaration takes just one line, but the body of the class declaration may take hundreds of lines. Or thousands if you get carried away.
The class body can contain the following elements:
-
Fields: Variable declarations define the public or private fields of a class.
-
Methods: Method declarations define the methods of a class.
-
Constructors: A constructor is a block of code that's similar to a method but is run to initialize an object when an instance is created. A constructor must have the same name as the class itself and, although it resembles a method, it doesn't have a return type.
-
Initializers: These are stand-alone blocks of code that are run only once, when the class is initialized. There are actually two types, called static initializers and instance initializers. Although you won't use them often, I talk about instance initializers later in this chapter, in the section "Using Initializers." (For information about static initializers, refer to Book III, Chapter 3.)
-
Other classes and interfaces: A class can include another class, which is then called an inner class or a nested class. Classes can also contain interfaces. (For more information about inner classes, see Book III, Chapter 7. And for information about interfaces, refer to Book III, Chapter 5.)
Tip | Unlike some programming languages, Java doesn't care about the order in which items appear in the class body. Still, being consistent about the order in which you place things in your classes is a good idea. That way you know where to find them. I usually code all the fields together at the start of the class, followed by constructors and then methods. If the class includes initializers, I place them near the fields they initialize. And if the class includes inner classes, I usually place them after the methods that use them. |
Some programmers like to place the fields at the end of the class rather than at the beginning. Whatever brings you happiness is fine with me.
TECHNICAL STAUFF | The fields, methods, classes, and interfaces contained within a class are called the members of the class. Constructors and initializers aren't considered to be members, for reasons that are too technical to explain at this point. (You can find the explanation in Book III, Chapter 3.) |
Where classes go
A public class must be written in a source file that has the same name as the class, with the extension java. For example, a public class named Greeter must be placed in a file named Greeter.java.
As a result, you can't place two public classes in the same file. For example, the following source file (named DiceGame.java) won't compile:
public class DiceGame
{
public static void main(String[] args)
{
Dice d = new Dice();
d.roll();
}
}
public class Dice
{
public void roll()
{
// code that rolls the dice goes here
}
}
The compiler coughs up a message indicating that Dice is a public class and must be declared in a file named Dice.java.
This problem has two solutions. The first is to remove the public keyword from the Dice class:
public class DiceGame
{
public static void main(String[] args)
{
Dice d = new Dice();
d.roll();
}
}
class Dice
{
public void roll()
{
// code that rolls the dice goes here
}
}
The compiler gladly accepts this program.
Tip | This is not the same thing as an inner class. An inner class is a class that's defined within the body of another class, and is available only from within that class. (For more information about inner classes, see Book III, Chapter 7.) |
TECHNICAL STAUFF | When you code more than one class in a single source file, Java still creates a separate class file for each class. Thus, when you compile the DiceGame. java file, the Java compiler creates two class files-named DiceGame.class and Dice.class. |
Removing the public keyword from a class is acceptable for relatively small programs. But its limitation is that the Dice class is available only to the classes defined within the DiceGame.java file. If you want the Dice class to be more widely available, opt for the second solution: Place it-with the public keyword-in a separate file named Dice.java.
Tip | If you're going to create an application that has several public classes, create a separate folder for the application. Then, save all the class files for the application to this folder. If you keep your class files together in the same folder, the Java compiler can find them. If you place them in separate folders, you may need to adjust your ClassPath environment variable to help the compiler find the classes. |
No comments:
Post a Comment