Packages in Java
April 11, 2010 at 12:08 pm Leave a comment
Packages are containers for classes. They keep classes into diff compartments. Hence provide a visibility control mechanism.
Define a package:
package <package_name>;
or
package <package_name1>.<package_name2>.<package_nameN>;
Underlying files should be present exactly into a similar pathed directory as of your package hierarchy.
If you omit package declaration, java puts them into default package which has no name.
A package may contain more than one files.
package java.awt.image:
Directory system will include:
Windows : java/awt/image
Linux : java\awt\image
Mac : java:awt:image
Example:
package MyPack;
Class Bname {
String name;
Bname( String nn)
{
name = nn;
}
void show() {
sop("My name is " + name);
}
}
Class Aname {
psvm(String args[]){
Bname bobj = new Bname("Prayas");
bobj.show();
}
}
Compile:
java Aname // Error, coz it can not be executed by itself
java MyPack.Aname // works .. must be qualified by its package name.
Access Protection:
a) For class members:
Private : Only within the package’s, within the class.
Protected: Within the package all classes/subclasses/other classes. In other package only the subclasses.
Public : within the package, in other packages.. hence everywhere
Default : <no access modifier has been mentioned> Within the package everywhere, outside the package no one, not even subclass
b)For class itself:
Private : Class cant be decalared as private
Protected : Class cant be decalared as protected
Public : Others can access, in other packages too.
Default: Within the same package.
Importing Packages:
The import statment occurs imm after the package name and before any class definitions.
import <package1>.<package2>.(classname | * )
import starts with a package name and ends with a classname or * (in case you want to include all the classes).
* may increase the compilation time for a larger package but it has no effect on the run-time performance of the size of your classes.
There arer NO core Java classes in the unnamed defualt package.
All the std classes are stored in some named package “java”.
The basic language functions are stored in “java.lang” and it is implicitly imported by the compiler. Hence need not to import.
Example
import java.util.*;
class MyDate extends Date {
}
The same could be written without using import
class MyDate extend java.util.Date {
}
Ref: The Complete Reference Java2 – Herbert Schildt



Trackback this post | Subscribe to the comments via RSS Feed