150 likes | 516 Views
Java Packages. Packages. A Package is a group of classes available for download and use java.lang is a predefined package that is automatically available to all Java programs String class is part of the java.lang package
E N D
Packages • A Package is a group of classes available for download and use • java.lang is a predefined package that is automatically available to all Java programs • String class is part of the java.lang package • string manipulation methods available in this class (check out Java documentation)
Packages • To use a package (other than java.lang) it must be imported into your Java program • import myPackage.*;will make all classes in package myPackage accessible to your class • import myPackage.class1;will make class1 in package myPackage accessible to your class • packages are imported at the top of the source code before any class definitions
Java packages • Java Packages available with the JDK • java.io – for system input and output • java.math – for integer and decimal arithmetic • java.text - for handling text, dates, numbers … • java.util – for collections, date & time facilities... • java.net – for implementing networking apps • java.sql – for accessing data in a data source • and many more…
Creating a Package • Groups of classes which are related can be placed in a package • Each source file that is to be part of the package must include package packageName;at the start of the source code • The class files for the package must be placed in a directory with the same name as the package
Classpath • To access a package (other than the standard JDK packages) your program must know where the package’s class files are located • The “classpath” indicates to the java compiler and JRE where class files are located • The classpath is set using the –classpath option on the compiler and the JRE
Classpath • to compile a class allowing access to other class files: javac –classpath pathSpec className.java • to run a Java application allowing access to other class files java –classpath pathSpec className • where pathSpec is the file specification of the directory that the package directory is in (i.e. the parent directory of the package directory)
Classpath Example • Consider a package called myPackage containing ClassX and ClassY • Class files should be placed in directory c:\subdir1\myPackage • i.e. c:\subdir1\myPackage\ClassX.class and c:\subdir1\myPackage\ClassY.class • classpath is then c:\subdir1 • e.g javac –classpath c:\subdir1 test.java • multiple filespec can be included in classpath, • e.g. javac –classpath c:\subdir1;d:\folderz\dir; …