0% found this document useful (0 votes)
33 views

Java Package

Java Packages Text book notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
33 views

Java Package

Java Packages Text book notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 8
Ye 11.2 JAVA API PACKAGES lasses grouped into. diferent pq ides a large number of cl P i Ickage, funationaliyy Most ofthe Wn-Wer Use the Packages available with the Java any “92s unctionality. cl . I. Figyps rg the functional breakdovin of packages thal are frequently used in the programe. Table ty Ma ght lasses that belong to each package (see Appendix B). Shon Java se lange) util 33) lope) ants) Det) Set) [GEREN Frequenty usea ap) packages Table 11.1 Java System Packages and Their Classes Packagename Contents Java. lang automatically imported. Th and exceptions. Classes for networking, They include Classes for communicating with local ‘computers as wells with internet ‘Servers. [Sava-applet Classes for creating and implementing applets, 11.3 USING SYSTEM PACKAGES te The packages are organi ure as illustrated in Fig, 11.2. This show fo Package named java contains the Package awt, which in turn contains various classes rea Implementing graphical user interiace veto user There are two ways of ar cessing the classes stored in a Package. The first approach tage na {ully qualified class name of the class that we want 0 use. This is done by using the pac Containing the class and ther mpl. if , xa GopPending the class name to i Using the dot operator. For Me want lo refer fo the class Color intheans Package, then we may do so as follows: java.awt.color ized ina hierarchical struct Packages: Putting Classes Together 207 Jawa Package containing awt package Graphics Package containing classes Classes containing methods [EERIES Hirarctica! presentation of java.awt package Notice that awt is a package within the package java and the hierarchy is represented by separating the levels with dots. This approach is perhaps the best and easiest one if we need to access the class only once or when we need not have to access any other classes of the package. But, in many situations, we might w. may like to use many of the classes cont fant to use a class in a number of places in the program or we tained in a package. We may achieve this easily as follows. import import pa These are know! declarations, import is a keyword. The first statement allows the speci the statement impor imports the class Color and therefore the class name can no is no need to use the package name to qualify the class. The second statement imports every class containe statement nas import statements and must appear at the top of the file, before any class ified class in the specified package to be imported. For example, java-awt Color; w be directly used in the program. There .d in the specified package. For example, the java.awt.* will bring all classes of java.awt package. 11.4 NAMING CONVENTIONS Packages can be named using the standard Java naming rules. By convention, however, packages begin with lowercase letters. This makes it easy for users to distinguish package names from class i licit reference to a class. We know that names when looking at an explicit tall class convention, begin with an uppercase letter. For example, look at the following tang | double y = java-lang Math, sqrt (x) ; package class method name name name This statement uses a fully qualified class name Math to invoke the method g rt methods begin with lowercase letters. Consider another example: A) Noy java.awt.Point pts[ Ji This statement declares an array of Point type objects using the fully qualified class nam Every package name must be unique to make the best use of packages. Dupioa will cause run-time errors. Since multiple users work on Internet, duplicate Package rant’ unavoidable. Java designers have recognized this problem and therefore suggested naming convention that ensures uniqueness. This suggests the use of domain names as pent 2 preferred package names. For example: te cbe.psg.mypackage Here cbe denotes city name and psg denotes organization name. Remember that we can cede, hierarchy of packages within packages by separating levels with dots. 11.5 CREATING PACKAGES We have seen in detail how Java system packages are organised and used. Now, let us see hw to create our own packages. We must first declare the name of the package using the pacha keyword followed by a package name. This must be the first statement in a Java source file (except comments and white spaces). Then we define a class, just as we normally define a class. Hereisat example: package firstPackage; / / package declaration public class FirstClass / / class definition { (body of class) } Here the package name is firstPackage. The class FirstClass is now considered a patt package. This listing would be saved as a file called FirstClass java, and located in a directo "™ firstPackage. When the source file is compiled, Java will create a .class file and store itn he directory. i Remember that the .class files must be located in a directory that has the same name @ i package, and this directory should be a subdirectory of the directory where classes that vil impo package are located. To recap, creating our own package involves the following steps: 4. Declare the package at the beginning ofa file using the form: package packagename; 2. Define the class that is to be put in the package and declare it publi ° t public. 3. Create a subdirectory under the directory where the main sourte: fice are stored. Packages: Putting Classes Together 209 4, Store the listing as the classname java file in the subdi 3. Compile the file. This creates .class file in the cubdhecen created. Remember that case is significant and therefore the een subdirectory name must match the package ‘as pointed out earlier, Java also supports the concept of package hi i p e hierarchy. pecifying multiple names in a package statement, separated by dots. Example: Ths is done by package first Package. secondPackage; This approach alate Us to group related classes into a package and then group related packages nos darger pac age. Remember to store this package in a subdirectory named firstPackage/ ‘A java package file can have more than one class definitions. In such cases, only one of the diasses may be declared public and that class name with java extension is the source file name. When a source file with more than one class definition is compiled, Java creates independent .class files for those classes. 11.6 ACCESSING A PACKAGE Itmay be recalled that we have discussed earlier that a Java system package can be accessed either using a fully qualified class name or using a shortcut approach through the import statement. We use the import statement when there are many references to a particular package or the package name is too long and unwieldy. The same approaches can be used to access the user-defined packages as well. The import statement can be used to search a list of packages for a particular class. The general form of import statement for searching a class is as follows: import packagel [.package2] [.package3].classnames Here package? is the name of the top level package, package?2 is the name of the package that is inside the package7, and so on. We can have any number of packages in a package hierarchy. Finally, the explicit classname is specified, Note that the statement must end with a semicolon (;). The import statement should appear before any class definitions in a source file. Multiple import statements are allowed. The following example of importing a particular class: import firstPackage . secondPackage -MyClassi After defining this statement, all the members of the class MyClass can be directly accessed using the class name or its objects (as the case may be) directly without using the package name. We can also use another approach as follows: import packagename. *; Here, packagename may denote a single package ! The star (+) indicates that the compiler should search this entire package hierarchy when it encounters class name. This implies that we can access all classes contained in the above package directly. The major drawback of the shortcut approach is that it is difficult to determine from which Package a particular member came. This is particularly true when a large number of packages are ree But the advantage is that we need not have to use long package names repeatedly in the ram, ora hierarchy of packages as mentioned earlier. 11.7 USING A PACKAGE Let tele’ ROW consider some simple programs that will use classes [rom other packages. The listing shows a package named packaget containing a single class ClassA. 210 Programming with Java public cla This source file should be named ClassA.java and stored in the subdirecto stated earlier. Now compile this java file. The resultant ClassA.class will be sto subdirectory, Now consider the listing shown below: D Kagel. Classa; "Y Pack red in ten g ClassA objecta = 1 ) objectA.displaya( ) This listing shows a simple program that imports the class ClassA from the package packip! The source file should be saved as PackageTestt.java and then compiled. The source fle anit compiled file would be saved in the directory of which package was a subdirectory. Now we cat? the program and obtain the results. During the compilation of PackageTest1 java the compiler checks for the file ClassA.classiat Package! directory for information it needs, but it does not actually include the code from Ch Class in the file PackageTest1.class. When the PackageTest1 program is run, Java looks frte® PackageTest1.class and loads it using something called class loader. Now the interpreter knoxst! italso needs the code in the file ClassA.class and loads it as well Now let us consider another package named package2 containing again a single class a8" below: package package public clas { protected int m= 10 Public void displayn( ) ( system printin("Class Bp"); ystem.out.printin(™m =” , A As usual, the source file and the com, package2. ut Program 11-1 shown below uses classes contained in both the packages and therelor at! Package1 and package2. Note that we have used Star instead of ‘explicit ‘class name i" package2 el Piled file of this package are located in the Packages: Putting Classes Togothor 214 Importing classes from other pac program 11.4 packagel. Cla: import import packag glass PackageTes ( public static void main(String argst 1) t ClassA objectA = new Cla de ClassB objectB = new ClassB( )7 objectA.displayA( ); object B.displayB( ); ) , This program may be saved as PackageTest2. java, compiled and run to obtain the results. The output will be as under class A Class B m= 10 When we import mi identical names. Example: \ultiple packages it is likely that two or more packages contain classes with package packl: public class Teacher f oe: public class Student a. . package pack2; public class Courses { a ) public class Student ‘ ) We may import and use these packages like: import packel import pack? Student student1; // create a student object anSite® both the packages contain the class Student. compiler cannot understand wihich one {0 oe herefore generates an error, In such instance, we have to be more explicit about which one we intend to use. Example: import pack .+ Sant Packs .< Packs Student tudent teache HOK // OK 77 No problem 77 No problem 212 Programming with Java It ig also possible to subclass a class that has been imported from another packag, illustrated by Program 11.2. The output will be: Thy Class B A Note that the variable m has been declared as protected. A subclass in another package can protected member. It would not have been possible ifit as been declared as either private or deay, Program 11.2. Subclassing an imported class // PackageTest3.java import package2.ClassB; class ClassC extends ClassB { int n = 20; void displayC( ) { System.out.printin(*Class C”); System.out.printin(*m =" + m); System.out.printin("n =” + n); ) ) class PackageTest3 { public static void main(String args[ }) { ClassC object = new Classc( ); objectC.displayB( ); objectC.displayc( ); __ While using packages and inheritance in a program, we should be aware of the visibility restos imposed by various access protection modifiers. As pointed out earlier, packages act as conta classes and other packages, and classes act as containers for data and methods. Data membe's ie methods can be declared with the access protection modifiers such as private, protected, and Lat as well as “default”. The effect of use of these modifiers was discussed in detail in chapter 8. Fo" sake of easy reference, the access protection details given in Table 8.1 are reproduced Table 12 11.8 ADDING A CLASS TO A PACKAGE itis simple to add a class to an existing package. Consider the a package pl: public classA ( } / 1 body of & Packages: Putting Classes Together 213 ——_—_s _ qable 11.2 Access protection Access ‘modifier public protected —_ friendly private private a (default rotect access. | eee eeeaeas location ‘Same class Yes Yes Yes Yes Yes ‘Subclass in same package Yes Yes Yes Yes No other classes in same package Yes Yes Yes No No subclass in other packages Yes Yes No Non-subclasses in other packages Yes No No No No ‘The package p1 contains one public class by name A. Suppose we want to add another class B to this package. This can be done as follows: 1. Define the class and make it public. 2. Place the package statement packai before the class definition as follows: ge pl // body of B 3. Store this as B.java file under the directory p1. ; 4. Compile B java file. This will create a B.class file and place it in the directory p1 Note that we can also add a non-public class to a package using the same procedure. Now, the package p1 will contain both the classes A and B. A statement like import pl. will import both of them. Remember that, since a Java source file can have only one class declared as public, we cannot put two or more public classes together in a java file, This is because of the restriction that the flle name should be same as the name of the public class with java extension. If we want to create a package with multip 1. Decide the name of the package. ; 2. Create a subdirectory with this name under the directory where main source files are stored. 3. Create classes that are to be placed in the package in separate source files and declare the package statement Ie public classes in it, we may follow the following steps: package packagename; at the top of each source file. 4. Switch to the subdirectory created earlier and compile each source file. When completed, the package would contain .class files of all the source files.

You might also like