You are on page 1of 11

5.

Packages
Topics:
Need for packages
What are packages; package declaration in
Java
Import statement in Java
How do packages resolve name clashes?

Package
Organize class name space
Hierarchical division must be reflected in directory structure,
i.e.,
package cyc.sys;
import java.io.*;
class Login { /* in fact, this is cyc.sys.Login */ }
Default packages (library) -- JDK
java.lang - Object, Thread, Exception, String,...
java.io - InputStream, OutputStream, ...
java.net - Networking
support for Socket & URL-based objects
java.awt - Abstract window toolkit
defines a simple, restricted windowing API
java.util - Hashtable, Vector, BitSet, Regexp, ..
java.tools - Compilation, Debugging, Documentation


Naming a Package
Package name should start with small alpha bate
only.
It can be any user defined name.
If super package is available then it must precede
sub package name.
Package statement must be the first statement in
.java file
There can be only one package statement in one
.java file.
Accessing package
If a package needs to be access outside current
package it must be imported by using import
statement.
The syntax is import
root_pkg.sub_pkg.Class/Interface name.
There can be multiple import statements within
same class.
You need not import java.lang (imported by
default).


User defined package
Create A package:->
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

Compiling the package:-> javac -d . Simple.java

Run the package as:-> java mypack.Simple

How to access package from another package?
There are three ways to access the package from outside the package:
1. import package.*;
2. import package.classname;
3. fully qualified name.
(If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.)

EX:
//save by A.java
package pack;
public class A{
public void msg(){
System.out.println("Hello");
}
}

//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

----OR----
pack.A obj = new pack.A();//using fully qualified name

Access specifiers
public: Any Class or any package.
private: class access (same as C++)
protected: sub class access + any class in same
package
Default : package access.
static: only one copy for all instances
abstract: left unimplemented
final: not overridden
native: methods implemented in native code.
synchronized: described in Thread
transient: data that is not persistent
Comparison
Specifier Class Subclass Package World
private X
protected X X X
public X X X X
package X X


1
Thank You

You might also like