0% found this document useful (0 votes)
9 views5 pages

Understanding Java Packages and Access Modifiers

Packages are used in Java to avoid naming conflicts and control access to classes. This document discusses what packages are, their benefits, types of packages, an example of creating and running a package, and how to access packages from other packages. It also covers the four types of access modifiers in Java - private, default, protected, and public - and what access they allow.

Uploaded by

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

Understanding Java Packages and Access Modifiers

Packages are used in Java to avoid naming conflicts and control access to classes. This document discusses what packages are, their benefits, types of packages, an example of creating and running a package, and how to access packages from other packages. It also covers the four types of access modifiers in Java - private, default, protected, and public - and what access they allow.

Uploaded by

Khan.ali
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Practical 09:- What is a Package ?

Write programs to create and use


package from the same package and also from a different package. Also
show the use of access specifiers.

1. Introduction

What is package:-
Packages are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of
classes, interface, enumeration or sub-package. Using package it becomes easier to locate
the related classes and it also provides a good structure for projects with hundreds of
classes and other files.

Benefits of using package in java:

1) Java package is used to categorize the classes and interfaces so that they can

be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

4) This packages can be provide reusability of code.

5) We can create our own package or extend already available package.

Types of Java Packages:-

• Built-in Package: Existing Java package for

example [Link], [Link] ,[Link] etc.

• User-defined-package: Java package created by user to categorize their

project's classes and interface.

Some of the java built-in functions are:

1) [Link]: Contains language support classes(e.g classed which defines


primitive data types,math operations). This package is automatically imported.
2) [Link]: Contains classed for supporting input / output operations.

3) [Link]: Contains utility classes which implement data structures like Linked
List, Dictionary and support ; for Date / Time operations.

4) [Link]: Contains classes for creating Applets.

5) [Link]: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).

2. Example of Java Package:-

package pk1;
public class Simple
{
public static void main(String args[])
{
[Link]("Welcome to package");
}
}

3. How to run java package program in Command line:-

You need to use fully qualified name e.g. [Link] etc to run the class.

To Compile: javac [Link]

To Run: java [Link]

Output: Welcome to package

4. Java File path setup :-

Java Virtual Machine(JVM) uses classpath to locate the class files to execute the code.
If your classpath is not set and the class file is not present in the same directory as your
java file, then JVM will be unable to find the required class file, and it will throw an
error.

Syntax for File path: >java -cp <directory_location> <class name>


5. How to access package from another package:

There are three ways to access the package from outside the package.

1. import package.*;

2. import [Link];

3. fully qualified name.

//Java Class A with package name PK1

package pk1;
public class A
{
int a;
protected int b;
private int c;
public d;

A()
{
a= -1;
b= -1;
c =-1;
d = -1;
void msg(){
[Link](“Hellow this code is inside PK1.“);
}
}
}

//Class B in same Package


package pk1;
public class B extend A
{
int e =0;
int f= 1;

B(){
[Link]("value of a: " + a);
[Link]("value of b: " + b);
// [Link](“value of c: “ + c); // error bcz c is private variable
[Link](“value of d: “ + d);
[Link](“value of e: “ + e);
[Link](“value of f: “ + f);
}

//Java Class C of same package


package pk1;
class C{
public static void main(String[] args){
A obj_A = new A();
B obj_B = new B();
}
}
/*Output

//Importing class from other package

package mypack; //creating Class B in new package mypack


import pk1.*;
class New_pack
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}

Output

There are four types of Java access modifiers:

• Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
• Default: The accesslevel of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will
be the default.
• Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
• Public: The access level of a public modifier is everywhere. It can be accessed from
within theclass, outside the class, within the package and outside the package.

Common questions

Powered by AI

Not setting the Java classpath correctly can lead to a situation where the Java Virtual Machine (JVM) is unable to locate class files necessary for execution, resulting in errors or failed execution of packages. This is because the JVM relies on the classpath to find the bytecode files to run a Java program. Without the correct path, even if the class files exist, the JVM won't be able to access and execute them, effectively halting the program unless the classes are present in the same directory as the Java files .

A Java package can be accessed from a different package using three methods: importing with 'package.*', importing a specific class with 'package.classname', and using the fully qualified name. Importing with 'package.*' imports all classes in the package, which could lead to unnecessary imports if only specific classes are needed. Importing a specific class is more efficient when only certain classes are used. Using the fully qualified name allows avoiding imports altogether but can make the code longer and harder to read .

The 'protected' access modifier in Java offers a broader range of access than the default modifier. While 'default' access restricts classes and members to be accessible only within the same package, 'protected' allows access not only within the same package but also from subclasses across different packages. This feature supports inheritance, enabling subclasses to utilize or override the protected members of their parent class, even if they belong to different packages .

Using 'import package.*' can negatively impact code readability and performance by cluttering the namespace with unused classes, making it difficult for developers to identify which classes are actually in use. This could lead to potential clashes during compilation. Conversely, 'import package.classname' enhances readability and performance by ensuring only the necessary classes are imported, which can reduce memory overhead and make it apparent which classes are being used in the codebase .

In class B, which extends class A in the same package, the output displays values of variables a, b, d, e, and f, but not c. Variable 'a' is accessed due to inheritance despite having default access; 'b' is accessible as it's protected and within the same package; 'd' is public, allowing universal access; variables 'e' and 'f' are local to class B. However, attempting to access 'c' results in an error since it is private to class A, rendering it inaccessible to any other class, even those in the same package or subclasses .

Built-in packages are predefined and provided by the Java platform. Examples include 'java.lang', 'java.util', and 'java.io', which contain classes for language support, utility data structures, and input/output operations, respectively. User-defined packages are created by developers to categorize their project’s classes and interfaces, making them specific to the needs of the project .

Access specifiers in Java define the scope of class member visibility. The 'private' specifier restricts access to within the class only; members cannot be accessed outside the class itself. The 'default' specifier allows access to class members from any class within the same package but restricts it for external packages. 'Protected' members are accessible within the same package and to subclasses in external packages, promoting inheritance. 'Public' members are accessible from anywhere, providing the least restriction. These access levels help encapsulate data, enhancing security and preventing unauthorized access or modification .

Java packages serve multiple purposes: they help avoid name conflicts by providing a namespace for related classes and interfaces; they contribute to code organization and management by categorizing classes/interfaces, which makes them easier to maintain; they enhance security by providing access protection through access specifiers; they enable code reusability; and finally, they eliminate naming collisions. For managing large projects with numerous classes, packages provide a structured and organized framework, making it easier to locate and maintain related classes .

Package reuse in Java fosters software development efficiency by allowing developers to leverage pre-defined or custom libraries of code rather than building functionalities from scratch. It enhances maintainability by encapsulating related classes and interfaces, allowing developers to comprehend and manage complex codebases more effectively. Reusing packages accelerates development and facilitates consistent updates across applications sharing the same package, minimizing errors and redundancies .

A developer might choose to create a user-defined package to organize and categorize their project's classes and interfaces in a way that suits the project's specific needs. This provides better maintainability and structure compared to using only built-in packages. Additionally, user-defined packages allow developers to extend existing functionality and develop custom solutions that are not available in built-in packages. They also reduce naming conflicts by providing a unique namespace .

You might also like