Public Classes in Java

The Account class in this example Java listing is public. A public class is available for use by all other classes. For example, if you write an ATMController program in some remote corner of cyberspace, then your ATMController program can contain code, such as myAccount.balance = 24.02, making use of the Account class declared. (Of course, your code has to know where in cyberspace you've stored the code, but that's another story.)

The first line of the code listing is

public class Account {

This listing example contains the code myAccount.balance = 24.02. You might say to yourself, "The Account class has to be public because another class uses the Account class."

Unfortunately, the real lowdown about public classes is a bit more complicated. In fact, when the planets align themselves correctly, one class can make use of another class's code, even though the other class isn't public.

The dirty secret in this code is that declaring certain classes to be public simply makes programmers feel good. Yes, programmers do certain things to feel good. In the listing, the programmer’s esthetic sense of goodness comes from the fact that an Account class is useful to many other programmers.

When you create a class that declares something useful and nameable — an Account, an Engine, a Customer, a BrainWave, a Headache, or a SevenLayerCake class — you declare the class to be public.

The UseAccount class in the listing is also public. When a class contains a main method, Java programmers tend to make the class public without thinking too much about who uses the class. So even if no other class makes use of the main method, you declare the UseAccount class to be public.

When you declare a class to be public, you must declare the class in a file whose name is exactly the same as the name of the class (but with the .java extension added). For example, if you declare public class MyImportantCode, you must put the class's code in a file named MyImportantCode.java, with uppercase letters M, I, and C and all other letters lowercase.

This file-naming rule has an important consequence: If your code declares two public classes, your code must consist of at least two .java files. In other words, you can't declare two public classes in one .java file.

public class Account {
    String name;
    String address;
    double balance;
}

The Account class in this listing defines what it means to be an Account. In particular, this listing tells you that each of the Account class’s instances has three variables — name, address, and 0.

This is consistent with the information in the figure. Java programmers have a special name for variables of this kind (variables that belong to instances of classes). Each of these variables — name, address, and balance — is called a field.

image0.jpg
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com