Implementing Packages | Komputasi | Suatu Permulaan

J.E.D.I

5.3 Implementing Packages

Packages provide a mechanism for software reuse. One of the goals of programmers is to create reusable software components so that codes are not repeatedly written. The Java Programming Language provides a mechanism for defining packages. They are actually directories used to organize classes and interfaces. Java provides a convention for unique package and class names. With hundreds of thousands Java programmers around the world, the name one uses for his classes may conflict with classes developed by other programmers. Package names should be in all-lowercase ASCII letters. It should follow the Internet Domain Name Convention as specified in X.500 format for distinguished names. The following are the steps in defining a package in Java. 1. Define a public class. If the class is not public, it can be used only by other classes in the same package. Consider the code of the Athlete persistent class shown in Text 9. The Athlete class is made public. 2. Choose a package name. Add the package statement to the source code file for a reusable class definition. In this example, the package name is abl.athlete.pc Software Engineering 206 package abl.athlete.pc; public class Athlete{ private int athleteID; private String lastName: private String firstName; ... the rest of the attributes set methods public void setAthleteID int id { athleteID = id; } ... the other set methods get methods public int getAthleteID { return athleteID } ... the other get methods } Text 9: Sample Package Definition J.E.D.I which is the name of the package for persistent classes and class lists. In the example, it is: package abl.athlete.pc; Placing a package statement at the beginning of the source file indicates that the class defined in the file is part of the specified package. 3. Compile the class so that it is placed in the appropriate package directory structure. The compiled class is made available to the compiler and interpreter. When a Java file containing a package statement is compiled, the result .class file is placed in the directory specified by the package statement. In the example, the athlete.class file is placed under the pc directory under the athlete which is under the abl directory. If these directories do not exist, the compiler creates them. 4. To reuse the class, just import the package. The statement shwon in Text 10 is an example of importing the Athlete class which is used by the DBAthlete class. Software Engineering 207 import abl.athlete.pc.; All public class of this package is available for DBAthlete use. public class DBAthlete{ private Athlete ath; defines a reference to an object Athlete ... the rest of the code } Text 10: Sample Package Importation J.E.D.I

5.4 Implementing Controllers