Packages.docx
Packages.docx
Packages in Java are a mechanism that encapsulates a group of classes, sub-packages, and
interfaces. Packages are used for:
● Prevent naming conflicts by allowing classes with the same name to exist in different
packages, like college.staff.cse.Employee and college.staff.ee.Employee.
● They make it easier to organize, locate, and use classes, interfaces, and other
components.
● Packages also provide controlled access for Protected members that are accessible
within the same package and by subclasses.
● Also for default members (no access specifier) that are accessible only within the
same package.
By grouping related classes into packages, Java promotes data encapsulation, making code
reusable and easier to manage. Simply import the desired class from a package to use it in
your program.
Working of Java Packages
Example:
import
java.util.*;
Here, util is a sub-package created inside the java package.
Simple example of java package
The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
Steps:
Output:Welcome to package
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }
1. //save by B.java
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
Output:Hello
Note: Sequence of the program must be package then import then class.
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Let's take an example, Sun Microsystem has definded a package named java that contains
many classes like System, String, Reader, Writer, Socket etc. These classes represent a
particular group e.g. Reader and Writer classes are for Input/Output operation, Socket and
ServerSocket classes are for networking etc and so on. So, Sun has subcategorized the java
package into subpackages such as lang, net, io etc. and put the Input/Output related classes in
io package, Server and ServerSocket classes in net packages and so on.
The standard of defining package is domain.company.package e.g. com.javatpoint.bean or
org.sssit.dao.
Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
class Student {
public static void main(String args[]) {