[Go to site: main page, start]

0% found this document useful (0 votes)
103 views4 pages

Java Package Creation and Usage Guide

Packages in Java are used to encapsulate related classes and prevent naming conflicts. Packages provide access control, make classes easier to find and use, and can be considered a form of data encapsulation. To create a package, include the package name statement at the top of a Java source file containing the classes for that package. A class can only belong to one package and packages allow reuse of existing classes.

Uploaded by

Kummeta Keerthi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
103 views4 pages

Java Package Creation and Usage Guide

Packages in Java are used to encapsulate related classes and prevent naming conflicts. Packages provide access control, make classes easier to find and use, and can be considered a form of data encapsulation. To create a package, include the package name statement at the top of a Java source file containing the classes for that package. A class can only belong to one package and packages allow reuse of existing classes.

Uploaded by

Kummeta Keerthi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • Packages in Java
  • Importing Packages in Java
  • Static Import in Java

Packages In Java

Package in java is a mechanism to encapsulate a group of classes, sub packages and

interfaces. Packages are used for:

 Preventing naming conflicts. For example there can be two classes with
name Employee in two packages, [Link] and
[Link]
 Making searching/locating and usage of classes, interfaces, enumerations
and annotations easier
 Providing controlled access: protected and default have package level
access control. A protected member is accessible by classes in the same
package and its subclasses. A default member (without any access
specifier) is accessible by classes in the same package only.
 Packages can be considered as data encapsulation (or data-hiding).

All we need to do is put related classes into packages. After that, we can simply write an
import class from existing packages and use it in our program. A package is a container
of a group of related classes where some of the classes are accessible are exposed
and others are kept for internal [Link] can reuse existing classes from the
packages as many time as we need it in our program

Creating a package in java:Creating a package in Java is a very easy task.

Choose a name for the package and include a package command as the first statement

in the Java source file. The java source file can contain the classes, interfaces,

enumerations, and annotation types that you want to include in the package. For

example, the following statement creates a package named MyPackage.

Including a Class in Java Package


To create a class inside a package, you should declare the package name as the first

statement of your program. Then include the class as part of the package. But,
remember that, a class can have only one package declaration. Here’s a simple

program to understand the concept.

package MyPackage;

public class Compare {


  int num1, num2;
  Compare(int n, int m) {
     num1 = n;
     num2 = m;
}
public void getmax(){
    if ( num1 > num2 ) {
     [Link]("Maximum value of two numbers is " + num1);
  }
    else {
     [Link]("Maximum value of two numbers is " + num2);
    }
}
public static void main(String args[]) {
Compare current[] = new Compare[3];
  current[1] = new Compare(5, 10);
    current[2] = new Compare(123, 120);
    for(int i=1; i < 3 ; i++)
    {
     current[i].getmax();
    }
 }
}
Output:

Maximum value of two numbers is 10


Maximum value of two numbers is 123

Creating a class inside package while importing another package:


 
package svew;
import [Link];
public class Demo{
    public static void main(String args[]) {
        int n=10, m=10;
        Compare current = new Compare(n, m);
        if(n != m) {
             [Link]();
        }
        else {
            [Link]("Both the values are
same");
        }  
}
}
Output:

1
Both the values are same
I have first declared the package svew, then imported the class Compare from the

package MyPackage. So, the order when we are creating a class inside a package

while importing another package is, 

  Package Declaration
  Package Import
    
If you do not want to use the import statement, there is another alternative to access a
class file of the package from another package. You can just use a fully qualified name
while importing a class.

Using fully qualified name while importing a class

Here’s an example to understand the concept. I am going to use the same package that

I have declared earlier in the blog, MyPackage.

 
Package svew;
public class Demo{
    public static void main(String args[]) {
        int n=10, m=11;
        //Using fully qualified name instead of import
        [Link] current = new [Link](n,
m);
        if(n != m) {
             [Link]();
        }
        else {
            [Link]("Both the values are same");
        }  
}
}
Output:

 
Maximum value of two numbers is
11

Static Import in Java


Static import feature was introduced in java from version 5. It facilitates the Java

programmer to access any static member of a class directly without using the fully

qualified name.

 
package MyPackage;
import static [Link].*; //static import
import static [Link].*;// static import
public class StaticImportDemo {
       public static void main(String args[]) {
          double val = 64.0;
          double sqroot = sqrt(val); // Access sqrt() method
directly
          [Link]("Sq. root of " + val + " is " + sqroot);
          //We don't need to use '[Link]
       }
    }
Output:
1
Sq. root of 64.0 is 8.0

Common questions

Powered by AI

A developer might choose to use static import in Java to access static members (methods and fields) of a class directly without qualifying their names with the class name. The main benefit is increased readability and simplicity of the code since the developer can call static methods or access static fields without repeatedly specifying the class. For example, using static methods like Math.sqrt() becomes sqrt() without the class prefix. This can make mathematical computations and other static method accesses appear cleaner, especially when a class involves numerous static references .

The 'protected' access modifier allows a field or method to be accessible within its own package and by subclasses. In Java, this means that any class in the same package can access protected members of another class. However, classes in different packages cannot access protected fields or methods unless they specifically belong to a subclass of the protected member’s class. This ensures a moderate level of encapsulation, offering flexibility to interact with inheriting classes while protecting class internals from undesired access by unrelated classes .

Data encapsulation in Java is reinforced through the use of packages by grouping related classes and controlling their accessibility. Packages serve as containers for classes, allowing some classes to be publicly accessible while others remain internal. This organization ensures that only necessary interfaces are exposed to other parts of the application, while implementation details remain hidden within the package. As a result, it provides a modular structure that helps manage complexity by encapsulating the data and behaviors within a defined boundary, promoting better information hiding and separation of concerns .

Creating a package in Java involves declaring a package name that allows developers to organize their classes, interfaces, and other components logically. This structure affects the organization and use of classes by providing a hierarchical namespace that simplifies class management. It also enforces a high-level design where developers can categorize and group classes based on functionality or module. By placing classes within packages, programs can better adhere to the principles of modularity and maintainability, as packages enable logical separation of code components, making it easier to import, manage dependencies, and maintain a clean and efficient code base .

The order of package declaration and import in Java is significant because the package declaration must be the first statement in a Java source file before any imports are made. This defines the namespace for the classes in the file and helps in organizing the classes into a package hierarchy. Only after declaring the package can you import other packages or classes, which allows the class to access or extend functionality from other parts of the program or other libraries that have been included .

Java handles potential naming conflicts through its package system, which allows classes with the same name to exist in different packages without conflict. Each package acts as a separate namespace. Thus, classes with identical names but located in different packages (e.g., college.staff.cse.Employee and college.staff.ee.Employee) can be distinguished through their fully qualified names. By importing these specific classes or accessing them with their full paths, developers can ensure clarity and avoid a clash between identically named classes .

Packages in Java encapsulate a group of related classes, sub-packages, and interfaces, which benefits developers by preventing naming conflicts, making classes easier to locate and use, and providing controlled access to classes. By relating classes in a specific package and controlling their accessibility using access modifiers such as 'protected' and default access, Java ensures that classes within the same package can share accesible properties, promoting encapsulation and information hiding .

A 'fully qualified name' provides an alternative to using an import statement by allowing developers to directly reference a class with its complete package path in the code. This means that instead of importing a package and all its classes at the beginning of a file, a developer can simply use the package name along with the class name wherever the class is needed. This can be useful to avoid potential conflicts or when using only a few classes from a package without cluttering the namespace .

The heavy use of static imports in Java, particularly in larger codebases, can reduce code readability and maintainability. It can lead to confusion about which class a static member belongs to, as static imports omit class names, making it difficult for developers to track the origin of a method or variable, thus increasing the cognitive load on the reader. Moreover, it can cause naming conflicts when multiple classes have static methods or fields with the same name, complicating debugging and maintenance tasks. Proper use of static imports requires careful organization and documentation to mitigate these issues .

Package-level access modifiers, such as the default access (no explicit modifier) and 'protected', affect class visibility by restricting or granting access to class members within the same package. Classes and members with default access are only accessible within the same package, making it easier to manage dependencies and maintain internal interfaces. In contrast, classes in different packages cannot access these members unless they are explicitly given public access or structure as part of their subclass. This control ensures that the package's internal workings are insulated from external interference, maintaining encapsulation .

Packages In Java
Package in java is a mechanism to encapsulate a group of classes, sub packages and 
interfaces. Packages are
remember that, a class can have only one package declaration. Here’s a simple 
program to understand the concept.
package MyP
        if(n != m) {
             current.getmax();
        }
        else {
            System.out.println("Both the values
            System.out.println("Both the values are same");
        }  
}
}
Output:
 
Maximum value of two numbers is 
11
Sta

You might also like