13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

82Chapter 3An Experienced Programmer’s Introducti<strong>on</strong> to Java3.3USING (AND MAKING) JAVA APISWith every class you write, you define a name—the name of the class. But whatif some<strong>on</strong>e else has already used that name? Java programming should encouragereuse of existing code, so how do you keep straight which names areavailable?This is a namespace issue—who can use which names. A classic way tosolve a namespace issue is to divide the namespace up into domains. On theInternet, host names are secti<strong>on</strong>ed off into domains, so that I can have a hostnamed Pluto or www and so can lots of others—because each host is qualifiedby its domain (e.g., myco.com). Thus www.myco.com isn’t c<strong>on</strong>fused withwww.otherco.com or www.hisgroup.org. Each host is named www, but eachis unique because of the qualifying domain.Java solves the problem in much the same way, but with the names in thereverse order. Think of the “host” as the class name; the “domain” name, usedto sort out identical host names, is, in Java parlance, the package name. Whenyou see a name like com.myco.finapp.Account, that can be a Java packagecom.myco.finapp qualifying a class named Account.Bey<strong>on</strong>d just keeping the namespace clean, Java packages serve anotherimportant functi<strong>on</strong>. They let you group together similar classes and interfacesto c<strong>on</strong>trol access to them. Classes within the same package can access eachothers’ members and methods even when they are not declared public, providedthey are not declared to be private. This level of intimacy, sometimescalled package protecti<strong>on</strong>, means that you should group classes together that arerelated, but avoid grouping too many classes together. It’s tempting just toput all your classes for a project into the same package, for example,com.myco.ourproject, but you will provide better safety and perhaps promotebetter reuse by grouping them into several smaller packages, for example,com.myco.util, com.myco.financial, and com.myco.gui.3.3.1 The package StatementSo how do you make a Java class part of a package? It’s easy—you just put, asthe first (n<strong>on</strong>comment) line of the file, the package statement, naming thepackage to which you want this class to bel<strong>on</strong>g. So if you want your Accountclass to be part of the com.myco.financial package, your Java code wouldlook as shown in Example 3.23.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!