[go: up one dir, main page]

0% found this document useful (0 votes)
24 views32 pages

Chapter 5 - Packages

Packages in Java

Uploaded by

donmitchell45
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)
24 views32 pages

Chapter 5 - Packages

Packages in Java

Uploaded by

donmitchell45
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
You are on page 1/ 32

Object Oriented Programming

Instructor: Solomon (Ph.D)


Chapter 5: Packages
Packages
• In Java, a package is a way to bundle together related
classes, interfaces, sub-packages and so on.
• Important characteristics of packages are:
1) Code Organization: They bundle related classes and interfaces
into packages.
2) Namespace Management: Each package in Java creates a new
namespace, which helps to avoid name conflicts.
▪ Two classes in different packages can share the same name without
conflict because the package name forms part of the class’s full name.
3) Access Control: By using access modifiers like public, private,
protected, and default - you can control the visibility and
accessibility of your classes, interfaces, and their members.
4) Code Reusability: Since related classes and interfaces are
organized into packages, they can be reused easily across
different parts of an application or even across dissimilar
applications.
Packages …
5) Built-In and User-Defined: Java comes with many built-in
packages like java.util, java.io, java.lang, etc.,
which provide a vast array of ready-to-use classes and
interfaces. However, you can also define your own packages to
suit the requirements of your application.
6) Hierarchical Structure: Packages in Java are hierarchical,
meaning one can contain other packages, forming a directory-
like structure. This structure is reflected in their naming
convention.
How to Declare and Define a Package?
• The package keyword is used for creating a new
package in Java. It should be the first line of code in your
Java file.
• Here’s the general syntax:
– package packageName;
• Defining a package involves creating the Java classes
within that. Here’s an example:
//Save MyC1ass.java
package myPackage;

public class MyC1ass {


// Your code goes here
}

• Here, ‘myPackage’ is the package name, and ‘MyClass’


is a Java class that belongs to ‘myPackage’.
Naming Convention for Packages in Java
• Java has some widely accepted rules for naming packages
to ensure consistency and avoid conflicts:
▪ Lowercase letters: Package names should be in lowercase to
avoid conflict with class names and interfaces.
▪ Unique names: To avoid conflicts, use unique package names.
▪ No keywords: Java keywords should not be used as package
names.
How Packages Work in Java?
• Packages in Java are used to:
1) Prevent naming conflicts: Packages allow classes to be grouped
together. This means you can use the same class name in
different packages without causing a naming conflict.
2) Improve readability and organization: By grouping related
classes together in packages, your code becomes easier to
navigate and understand.
3) Control access: Packages can control access to classes and class
members.
▪ Java has a number of access modifiers (public, protected, no
modifier or default, and private) that determine the visibility of
classes and class members.
▪ For instance, class members marked as 'public' are accessible
from any other class, while those marked as 'private' can only be
approached from within the same class.
Types of Packages
• Packages can be categorized into two types: built-in
packages and user-defined packages.
1) Built-in Packages:
− They are also known as standard packages, these are part of the
Java Development Kit (JDK).
− They come pre-installed with Java and provide a wide range of
classes and methods for developers.
− Examples: java.lang, java.util, java.io, etc.
Types of Packages …
• Here’s an illustration of using a class (ArrayList) from
the built-in java.util package:
//Save Main.java
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
System.out.println(list);
}
}
Output: [Hello, World]
Types of Packages …
2) User-Defined Packages:
− These are packages created by developers to organize their
application’s code. You can define yours using the ‘package’
keyword.
− For example, you could create a package myapp.shapes and
define a Circle class in it:
//Save Circle.java
package myapp.shapes;
public class Circle { >javac -d . Circle.java
// Circle related code
}

– To use this Circle class in another package, you would import it


like this:
//Save Main.java
import myapp.shapes.Circle;
public class Main {
public static void main(String[] args) {
Circle myCircle = new Circle();
// Rest of the code
}
>javac -d . Main.java
} > java Main
Packages and Member Access
• The visibility of an element is affected by its access
specification - private, public, protected, or default
and the package in which it resides.
• Thus, as it relates to classes and packages, the
visibility of an element is determined by its visibility
within a class and its visibility within a package.

• The following table (Class member access)


summarizes the various access levels. Let’s examine
each access option individually.
Packages and Member Access …
Private Default Protected Public
Member Member Member Member
Visible within Yes Yes Yes Yes
same class
Visible within No Yes Yes Yes
same package by
subclass
Visible within No Yes Yes Yes
same package by
non-subclass
Visible within No No Yes Yes
different package
by subclass
Visible within No No No Yes
different package
by non-subclass
Packages and Member Access …
• If a member of a class has no explicit access modifier,
then it is visible within its package but not outside its
package. Therefore, you will use the default access
specification for elements that you want to keep private
to a package but public within that package.
• Members explicitly declared public are the most visible,
and can be accessed from different classes and different
packages.
• A private member is accessible only to the other
members of its class. A private member is unaffected by
its membership in a package.
• A member specified as protected is accessible within its
package and to subclasses in other packages.
Packages and Member Access …
• The above table applies only to members of classes. A
top-level class has only two possible access levels: default
and public.
– When a class is declared as public, it is accessible outside its
package.
– If a class has default access, it can be accessed only by other code
within its same package. Also, a class that is declared public must
reside in a file by the same name.
Simple example of Java package
• The package keyword is used to create a package in
java.
//save as Simple.java
package mypack;

class Simple {
public static void main(String[] args) {
System.out.println("Welcome to package");
}
}

• How to compile java package:


– javac -d Destination_folder file_name.java
– javac -d . Simple.java
• The -d switch specifies the destination where to put the
generated class file.
• You can use any directory name like /home (in case of Linux),
d:/abc (in case of windows), etc. If you want to keep the
package within the same directory, you can use . (dot).
How to run Java package program?
• You need to use fully qualified name e.g.
mypack.Simple to run the class.

• To Compile: javac -d . Simple.java


• To Run: java mypack.Simple

• Output: Welcome to package

• The -d is a switch that tells the compiler where to put the


class file i.e. it represents destination. The . represents
the current folder.
How to access package from another
package?
• There are three ways to access the package from outside
the package.
✓ import package.*;
✓ import package.classname;
✓ fully qualified name.
1) Using packagename.*
− If you use package.* then all the classes and interfaces of this
package will be accessible but not subpackages.
− The import keyword is used to make the classes and interface
of another package accessible to the current package.
How to access package from another
package? …
• Example of package that import the packagename.* is
as follows:
//save by A.java
package pack;

public class A {
public void msg() {
System.out.println("Hello"); >javac –d . A.java
}
}
//save by B.java
package mypack;
import pack.*;

class B {
public static void main(String[] args) {
A obj = new A();
obj.msg();
} >javac –d . B.java
} >java mypack.B
Output: Hello
How to access package from another
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
//save by A.java
package pack;

public class A {
public void msg() {
System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.A;

class B {
public static void main(String[] args) {
A obj = new A();
obj.msg();
}
}
Output: Hello
How to access package from another
package? …
3) Using fully qualified name:
− If you use fully qualified name then only declared class of this
package will be accessible. Now there is no need to import. But
you need to use fully qualified name every time when you are
accessing the class or interface.
− It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.
How to access package from another
package? …
• Example of package by using import fully qualified name:
//save by A.java
package pack;

public class A {
public void msg() {
System.out.println("Hello");
}
}
//save by B.java
package mypack;

class B {
public static void main(String[] args) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output: Hello
How to access package from another
package? …
• If you import a package, all the classes and interface of
that package will be imported excluding the classes and
interfaces of the subpackages. Hence, you need to import
the subpackage as well.
• Note: Sequence of the program must be package then
import then class.
Sub-package in Java
• Package inside the package is called the sub-package. It
should be created to categorize the package further.
• Let us take an example, Sun Microsystem has defined 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 used for Input/Output operation, Socket and
ServerSocket classes are used for networking, and so on.
− So, Sun Microsystem has subcategorized the java package into
subpackages such as lang, net, io, etc. - and they put the
Input/Output related classes in io package, Server and
ServerSocket classes in net package and so on.
Example of Subpackage
//save Simple.java
package com.test;

class Simple {
public static void main(String[] args) {
System.out.println("Hello subpackage");
}
}
To Compile: javac -d . Simple.java
To Run: java com.test.Simple

Output: Hello subpackage


How to send the class file to another
directory or drive?
//save as A.java
• There is a scenario to package mypack;

put the class file of public class A {


A.java source file in public static void main(String[] args) {
System.out.println("Welcome to package");
classes folder of }
C:drive. }

• For example, • To Compile:


E:\sources> javac -d C:\classes A.java

• To Run:
− To run this program from E:\source
directory, you need to set classpath of
the directory where the class file
resides.
E:\sources> set classpath=C:\classes;.;
E:\sources> java mypack.A
How to send the class file to another
directory or drive? …
• Another way to run the above program by -classpath
switch of Java:
− To run this program from E:\sources directory, you can use -
classpath switch of java that tells where to look for class file.
− For example:
E:\sources> java -classpath C:\classes mypack.A

− Output: Welcome to package


Ways to load the class files or jar files
• There are two ways to load the class files: temporarily and
permanently.
− Temporary:
▪ By setting the classpath in the command prompt or
▪ By –classpath switch.
− Permanent:
▪ By setting the classpath in the environment variables or
▪ By creating the jar file, that contains all the class files, and
copying the jar file in the jre/lib/ext folder.
Using Static Import
• Java’s static import is a feature that allows members
(fields and methods) defined in a class as public static to
be used in Java code without specifying the class in which
the field is defined.
− This can lead to more readable and less verbose code.
• Normally, to access static members, you need to prefix it
with the class name like this:
− double result = Math.sqrt(25); // Using sqrt method from Math class
• But with static import, you can import the ‘sqrt’ method
once and use it directly in your code:
import static java.lang.Math.sqrt;

public class Main {


public static void main(String[] args) {
double result = sqrt(25); // Directly using sqrt without prefixing Math
System.out.println(result);
}
}
Using Static Import …
• In the above code, ‘sqrt’ method from
‘java.lang.Math’ is statically imported, and you can
use it directly without prefixing it with ‘Math’.
• However, caution is required when using static imports as
it may reduce readability if overused because it’s not clear
which class the method or field is coming from.
• They are generally employed for frequently used static
methods, like those from ‘java.lang.Math’.
• This mechanism of importing packages in Java makes your
code more readable and reduces verbosity.
Java’s Class Library is Contained in
Packages
• As explained earlier, Java defines a large number of
standard classes that are available to all programs. This
class library is often referred to as the Java API
(Application Programming Interface).
• The Java API is stored in packages. At the top of the
package hierarchy is java. Descending from java are
several subpackages. Here are a few examples:
Subpackage Description
java.lang Contains a large number of general-purpose classes.
java.io Contains I/O classes.
java.net Contains classes that support networking.
java.util Contains a large number of utility classes, including the
Collections Framework.
java.awt Contains classes that support the Abstract Window Toolkit.
Java’s Class Library is Contained in
Packages …
• java.lang contains, among several others, the
System class, which you have been using when
performing output using println().
• The java.lang package is unique because it is
imported automatically into every Java program. That is
why you did not have to import java.lang in the
preceding sample programs. However, you must explicitly
import the other packages.
Thank You!

You might also like