PACKAGES IN JAVA
How packages work?
•Packagenamesanddirectorystructurearecloselyrelated.
Forexampleifapackagenameiscollege.staff.cse,then
therearethreedirectories,college,staffandcsesuch
thatcseispresentinstaffandstaffispresentcollege.
•Also,thedirectorycollegeisaccessible
throughCLASSPATHvariable,i.e.,pathofparentdirectory
ofcollegeispresentinCLASSPATH.Theideaistomakesure
thatclassesareeasytolocate.
Packagenamingconventions:
•Packagesarenamedinreverseorderofdomainnames.For
example,inacollege,therecommendedconventionis
college.tech.cse,college.tech.ee,college.art.history,etc.
PACKAGES IN JAVA
Adding a class to a Package :
•We can add more classes to a created package by using package
name at the top of the program and saving it in the package
directory. We need a newjavafile to define a public class,
otherwise we can add the new class to an existing.javafile and
recompile it.
Subpackages:
•Packages that are inside another package are thesubpackages.
These are not imported by default, they have to imported explicitly.
Also, members of a subpackage have no access privileges, i.e., they
are considered as different package for protected and default
access specifiers.
Example :
•import java.util.*;
•utilis a subpackage created insidejavapackage.
PACKAGES IN JAVA
•Types of packages:
PACKAGES IN JAVA
Built-in Packages
ThesepackagesconsistofalargenumberofclasseswhichareapartofJavaAPI.Some
of the commonly used built-in packages are:
1)java.lang:Containslanguagesupportclasses(e.gclassedwhichdefinesprimitive
datatypes,mathoperations).Thispackageisautomaticallyimported.
2)java.io:Containsclassedforsupportinginput/outputoperations.
3)java.util:ContainsutilityclasseswhichimplementdatastructureslikeLinkedList,
Dictionaryandsupport;forDate/Timeoperations.
4)java.Applet:ContainsclassesforcreatingApplets.
5)java.awt:Containclassesforimplementingthecomponentsforgraphicaluser
interfaces(likebutton,;menusetc.).
6)java.net:Containclassesforsupportingnetworkingoperations.
PACKAGES IN JAVA
User-definedpackages
•
Thesearethepackagesthataredefinedbytheuser.
•FirstwecreateadirectorymyPackage(nameshouldbesameasthename
ofthepackage).
•ThencreatetheMyClassinsidethedirectorywiththefirststatement
beingthepackagenames.
PACKAGES IN JAVA
// Name of the package must be same as the directory
// under which this file is saved
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
PACKAGES IN JAVA
Now we can use theMyClassclass in our program.
/* import 'MyClass' class from 'names' myPackage*/
import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{
// Initializing the String variable
// with a value
String name = "GeeksforGeeks";
// Creating an instance of class MyClassin
// the package.
MyClassobj= new MyClass();
obj.getNames(name);
}
}
Note :MyClass.javamust be saved inside themyPackagedirectory since it is a part of the
package.