0% found this document useful (0 votes)
11 views11 pages

Understanding Java Packages and Access Modifiers

Uploaded by

lohithdadi64
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)
11 views11 pages

Understanding Java Packages and Access Modifiers

Uploaded by

lohithdadi64
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

JAVA - PACKAGES:

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.

Java Packages: Types:

 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.

How to Create a package:


Creating a package in java is quite easy. Simply include a package command
followed by name of the package as the first statement in java source file.
package mypackage;
public class student
{
Statement;
}
The above statement will create a package name mypackage in the project
directory.
Java uses file system directories to store packages. For example the .java file for
any class you define to be part of mypackage package must be stored in
a directory called mypackage.
Additional points about package:

 A package is always defined as a separate folder having the same name as


the package name.
 Store all the classes in that package folder.
 All classes of the package which we wish to access outside the package must
be declared public.
 All classes within the package must have the package statement as its first
line.
 All classes of the package must be compiled before use (So that they are
error free)
Example of Java packages:
Package mypack;
public class Simple
{
public static void main(String args[])
{
[Link]("Welcome to package");
}
}
How to compile Java packages:
This is just like compiling a normal java program. If you are not using any IDE, you
need to follow the steps given below to successfully compile your packages:
1. java -d directory javafilename

For example

javac -d . [Link]

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. [Link] etc to run the class.
To Compile: javac -d . [Link]
To Run: java [Link]

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.

1. import package.*;
2. import [Link];
3. 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.

Example of package that import the packagename.*:


//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello java");}
}

//save by [Link]
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}
Output: Hello java

2) Using [Link]:

If you import [Link] then only declared class of this package will be
accessible.

Example of package by import [Link]:


//save by [Link]

package pack;
public class A
{
public void msg()
{
[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;

class B
{
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}

Output: Hello

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. [Link] and
[Link] packages contain Date class.

Example of package by import fully qualified name:


//save by [Link]
package pack;
public class A
{
public void msg()
{
[Link]("Hello");}
}
//save by [Link]
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
[Link]();
}
Output: Hello

Note: If you import a package, subpackages will not be imported.

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 needto import the
subpackage as well.

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 andso 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.

package [Link];
class Simple{
public static void main(String args[]){
[Link]("Hello subpackage");
}
}
To Compile: javac -d . [Link]

To Run: java [Link]

Output: Hello subpackage

Access control/ Access Modifier


The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
 Private
 Default
 Public
 Protected
Private
}
A member is declared private using private keyword. This is the most restrictive access
modifier in java. The code below declares the variable countas private. The access level
of a private modifier is only within the class. It cannot be accessed from outside the
class. Variables, methods and constructors can be declared as private.
Note: A class cannot be private or protected except nested class.
class Am
{
private void msg()
{
[Link]("hi");
}
}
public class Amj
{
public static void main(String[] args)
{
Am obj=new Am();
[Link]();
}
}

Output:
[Link]: error: msg() has private access in Am
[Link]();

In the above code, msg() function can be accessed only within Am class. This code will
rise an error as we are making a method call from outside the class (Amj)

Default class
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package.
It cannot be accessed from outside the package. It provides more accessibility than
private. But, it is more restrictive than protected, and public.

// Consider a java file C_1.java


package pack_1;
class C_1
{
public void display1()
{
[Link](" pack_1 and class C_1 ");
}
}

// Consider a java file C_2.java


import pack_1.C_1;
class C_2
{
public static void main(String[] args)
{
C_1 obj=new C_1();
obj.display1();
}
}

Output: }

C_2.java:2: error: C_1 is not public in pack_1; cannot beaccessed


from outside package
import pack_1.C_1;

In the above 2 programs, class C_1 is default (As no access modifier is specified). This
class cannot be accessed outside the package pack_1. So, if we import the package
pack_1 and use it in class C_2, we get error.

Protected
The protected access modifier is accessible within package and outside the package
but through inheritance only. The protected access modifier can be applied on the data
member, method, and constructor. It cannot be applied on the class. It provides more
accessibility than the default modifier.

//Save as [Link]
package protj;
public class P
{
protected void msg()
{
[Link]("protected_testing");
}
}

//Save as [Link]
import protj.*;
class Q extends P
{
public static void main(String[] args)
{
Q obj=new Q();
[Link]();
}
}

Output:
protected_testing

In the above code, method msg() in class P of package protj can be accessed outside
the package in class Q. This is possible because class Q extends class P.

Public
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers. The public access modifier is accessible everywhere. It has the widest
scope among all other modifiers.
Output:
pack_1 and class C_1

display() function in class C_1 can be accessed anywhere (i.e. Inside class, outside
}
class, inside package and outside the package)
// Consider a java file C_1.java
package pack_1;
public class C_1
{
public void display1()
{
[Link](" pack_1 and class C_1 ");
}
}

// Consider a java file C_2.java


import pack_1.C_1;
class C_2
{
public static void main(String[] args)
{
C_1 obj=new C_1();
obj.display1();
}
}

The following tables shows the accessibility/visibility scope of a member for


different access modifiers in java.
Access Modifier within within outside outside
class packag package by packag
e subclass only e
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

[Link] package
The package [Link] contains classes and interfaces that are essential to the Java
programming language. This [Link] package contains Object, Thread, String etc.
Object class is the ultimate super class of all classes in Java. Thread class that controls
each thread in a multi-threaded [Link] classes in the [Link] package are so
essential, the [Link] package is implicitly imported by every Java source file. In other
words, you can refer to all of the classes and interfaces in [Link] using their simple
names.

Classes in [Link] package

1) Wrapper classes
The wrapper class in Java provides the mechanism to convert primitive into object and
} primitive.
object into
Autoboxing and Unboxing feature convert primitives into objects and objectsinto
primitives.
Wrapper classes are used for:
 Java supports only call by value. So, if we pass a primitive value, it will
not change the original value. But, if we convert the primitive value in
an object, it will change the original value.
 The classes in [Link] package handles only objects and
hence wrapper classes help in this case also.
 Data structures in the Collection framework such as ArrayList and Vector
store only the objects (reference types) and not the primitive types.

The eight classes of the [Link] package are known as wrapper classes in Java.
These are,
primitive Wrapper
Type class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Autoboxing
Conversion of primitive data type into its corresponding wrapper class is known as byte
to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean,
double to Double, and short to Short.

public class WrapperExample1{


public static void main(String args[]){
//Converting int into Integer
int a=20;
Integer i=[Link](a);//converting int into Integer explicitly, boxing
Integer j=a;//autoboxing, now compiler will write [Link](a) internally
[Link](a+" "+i+" "+j);
}
}
• Ouput:
• 20 20 20

AutoUnboxing
The automatic conversion of wrapper type into its corresponding primitive type is known
as unboxing. It is the reverse process of autoboxing.

public class WrapperExample2{


public static
} void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=[Link]();//unboxing, converting Integer to int explicitly
int j=a;//Autounboxing, now compiler will write [Link]() internally
[Link](a+" "+i+" "+j);
}
}
Output:
333

Java util package


Java util package contains collection framework. Java collections framework contains
collection classes, classes related to date and time, event model, internationalization,
and miscellaneous utility classes. On importing this([Link] ) package, you can do
access all these classes and methods.

Arrays
This class contains various methods for manipulating arrays (such assorting and
searching). Due to these helpful various methods, Arrays class are definitely a
must to learn.

Calendar
The Calendar class is an abstract class that provides methods for
converting between a specific instant in time and a set of calendar fields such as YEAR,
MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields,
such as getting the date of the next week.

Currency
This class represents Currency. Anything that got to do with currency, this class will be
helpful.

HashMap
Hash table based implementation of the Map interface.
HashSet This class implements the Set interface, backed by a hash table (actually
a HashMap instance).

Scanner
A simple text scanner which can parse primitive types and strings using Regular
expressions.

StringTokenozer
The StringTokenizer class as the name implies allows an application to break a string
into tokens.

Collections Framework in Java


A collection sometimes called a container is simply an object that groups multiple
elements into a single unit. Collections are used to store, retrieve, manipulate, and
communicate aggregate data in Java .
 A collection is the same as the intuitive, mathematical concept of a set.
A set is just a group of unique items, meaning that the group contains
} no duplicates.
 Java Collections Framework provides a set of interfaces and classes for
storing and manipulating groups of data as a single unit, a collection.
 The framework provides a convenient API to many of the abstract data
types maps, sets, lists, trees, arrays, hashtables, and other collections.
 Because of their object-oriented design, the Java classes in the
Collections Framework encapsulate both the data structures and the
algorithms associated with these abstractions.
 With the Java Collections Framework the programmer easily define
higher level data abstractions, such as stacks, queues, and thread safe
collections.

You might also like