Packages
Packages
Presented by
Ms.G.Sakthi Priya, AP/CSE
Introduction
• Unique name had to be used for each class to avoid name collisions.
• Name you choose for a class will be reasonably unique and not
collide with other class names
For example, a package allows you to create a class named List,
which you can store in your own package without concern that it will
collide with some other class named List stored elsewhere
• Java provides a mechanism for partitioning the class name space into
more manageable chunks. This mechanism is the package
• The package is both a naming and a visibility control mechanism.
• You can define classes inside a package that are not accessible by
code outside that package
• You can also define class members that are exposed only to other
members of the same define class members that are exposed only to
other members of the same package
• This allows your classes to have intimate knowledge of each other,
but not expose that knowledge to the rest of the world
Package
• Packages are containers for classes. They are used to keep the
class name space compartmentalized.
• A Java package is a mechanism for organizing similar type of
Java classes, sub packages and interfaces into namespaces.
• Each package in Java has its unique name and it helps
organize the classes into a folder structure and make it easy
to locate and use them.
• Packages are stored in a hierarchical manner and are explicitly
imported into new class definitions.
Which package is always imported by default in Java?
}
}
class AccountBalance{
public static void main(String[] args){
Balance current = new Balance("Tom",12345);
current.show();
}
Importing Packages
• Import statement allows to import the entire package or certain
classes/interface
Example:
• import java.util.Date;
• import java.io.*;
Example with the import Example without the import statement
statement class MyDate extends java.util.Date {
import java.util.*;
class MyDate extends }
Date {
import mypack.Balance;
Example: class AccountBalance{
public static void main(String[] args){
Balance current = new Balance("Tom",12345);
package mypack; current.show();
public class Balance{ }
String name; }
double bal;
public Balance(String n, double b){
name = n;
bal = b;
}
public void show(){
System.out.println(name + " Rs "+ bal);
Not accessible in
different package
Explanation
• Inside the "p1" package, there exists a class named "Protect" with a
default variable named "def," which is initialized with a value of 3.