0% found this document useful (0 votes)
7 views10 pages

Java Packages and Interfaces Explained

Uploaded by

SAMANVITA Rd
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)
7 views10 pages

Java Packages and Interfaces Explained

Uploaded by

SAMANVITA Rd
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

AVA

PART A i Porcke s

CHAPTER
9
Packages and Interfaces

his chapterexamines two of Java's most innovative features: packages and interfaces.

(Packages)are containers are used to keep the class namne space


for classes that
compartmentalized. For example, a package allows you to create a class named List,
which you can store in your own package without concern that will collide with some

it
other class named List stored [Link] are stored in a hierarchical manner and
arejexplicitly imported into new class definitions.
In previous chapters, you have seen how methods define the interface to the data in
a Through the use of the interface keyword, Java allows you to fully abstract the
class.

interface from its implementation. Using interface, you can specify a set of methods that
can be implemented by one or more classes. The interface, itself, does not actually define
any implementation. Although they are similar to abstract classes, interfaces have an
additional capability: A class can implement more than one interface. By contrast, a class
can only inherit a single superclass (abstract or otherwise).

Packages
In the preceding chapters,the mame of each example clss)was taken from the same
name space. means that alunique name)had to be used for each class to avoid name
This

collisions, After a while, without someway to managethe name space, you could run out

of convenient, descriptive names for individuàl classes. You also need some way to be
assured that the name you choose for a class will be reasonably unique and not collide
with class names chosen by other programmers. (Imagine a small group of programmers
fighting over who gets to use the name "Foobar" as a class name. Or, imagine the entire
Internet community arguing over who first named a class "Espresso.") Thankfully,Java
provides almechanism for partitioning thelass name space) into more manageable
chunks. This mechanism is the/package The package is bothanamingland avisibility
Control [Link] can define classes inside a package that are not accessible by
code outstde that package, You can also define class members that are only exposed
to members of the same package. This allows Four classes to haveintimate
other

knowledge of each other, but not expose tht knowledge to the rest of the world.

Packeases

uses ceßned Bu 183


patkoges
packoges Package)

jovaio net
Jevq ast
tasses
daashcko nlw
184 Part I: The Java Language

Defining a Package
command as the first statement
Tocreate a package is quite easy: simply include apackage
within that file will belong to the specified package.
in a Java source file, Any classes declared

The package statement defines. a name space in which classes are stored. If you omit the
package statement, the class names ar put into the default package, which has no name.
(Thisiswhy you havent had to worry about packages before now.) While the default package
is fine for short, sample programs, it is inadequate for real applications. Most of the time,
you will define a packageforyour,code.
This is the general form of the package statement:

package pkg:

Here,pkgjis the name of thepackage. For example, the followingstatement creates a package
called MyPackage.

package MyPackage;

Java usesfile system directories tostore [Link] example, the .class files for
any
you declare to be part of MyPackage must be stored in a directory called MyPackage.
classes

Rememberthat case is significant, and the directory name must match the package name
exactly.

More than one file can include the same package statement. The
package statement
simply specifies to which packagethe classes defined in a file belong. does not exclude
It
other classes in other files from being
part of that samepackage. Most real-world packages
are spread across many files.
You can create ahierarchy packagesTo do so, simply separate each package name
of
fromthe one above by use of a period. The general form of a multileveled
package statement
it
is shownhere:

package pkgl[pkg2[,pkg3]]:

A package hierarchy must be reflected inthe file system of your Java development
[Link] example, a package declared as

package [Link];

needs to be stored in java\awt\image in a Windows environment. Be sure to choose


your
package namescarefully. You cannot rename a package without renaming
the directory in
which the classes are stored.

Finding Packages and CLASSPATH


As just explained, packages are. mirrored by directories.
This raises an important question:
How does the Java run-time system know wheretolook
for packages that you create?
The
answer hasthree parts Firstby th
default, run-time system uses the current working
Java
directory as its starting Thus,if
pojnt. your package is ina subdirectoryof the current
directory, it will be [Link], you can specify a directory path or paths by setting the
Chapter 9: Packages and Interfaces 185

CLASSPATH environmental variable Third,you can use the -classpath option with java
and javacto specify the path to your classes.

For example, consider the following package specification:

package MyPack
PARTI

In order fora program to find MyPack,one of three things must be true. Either the program
can be executed from a directory immediately above MyPack, orthe CLASSPATH mustbe
to include the path to MyPack,or the -classpath
set option must specify the path to MyPack
when the program is run via java.
When thesecond two options are used, the class path must not include MyPack,itself.
It must simplyspecifythe path to [Link] example, in a Windowsenvironment, if the
path to MyPack is
C:\MyPrograms\Java\MyPack

Then the class path to MyPack is


C:\MyPrograms\Java

The easiest way to try the examples shown in this book is to simply create the package
directories below your Current development directory, put the .class files into the
directories, and then execute the programs from the development directory.
appropriate
This is the approach used in the following example.

A Short Package Example


Keeping the preceding discussion in mind, you can try this simple package:

1/A simple package


package MyPack;

class Balance
String name;
double bal;

public Balance (String n, double b){


name = n;
bal = b;

void show () {

public if (bal<0)
System. [Link] ("- -> );
System.,out .println (name + ": $" + bal) ;

import lack Balance.


class AccountBalance
public static void main (tring args ) [] {

Balance current [] = new Balance [3];


186 Part I: The Java Langu age

123.23) ;
Balance ("K. J. Fielding",
current [0) = new 157.02) ;
("Will Tell",
current [1) = new Balance -12.33);
("Tom Jackson",
current [2] = new Balance

[i) .show();
for (int i=0; i<3; i++) current

a directorycalled MyPack.
Call this [Link] and put it in
the .class file is also in the MyPack
Next, compile the file. Make sure that
resulting

class, using the following


command line:

directory. Then, try executing the AccountBalançe

java MyPack. AccountBalance

above MyPack when you execute this command.


Remember, you wil need to beinthe directory
two options described in thepreceding section to
(Alternatively youlcan use one of the other

the path MyPack.)


specify
part of the package MyPack. This means that it
As explained, AccountBalance is noW
That is, you cannot use this command line:
cannot be executed by itself.

java AccountBalance

AccountBalance must be qualified with its package name.

Access Protection
various aspects of Java's access control mechanism
In the preceding chapters,you learned about
already know that access to a private member of
and its access specifiers. For example, you
that class. Packages add another dimension
to
a class is granted only to other members
of

access control. As you will see, Java provides


many levels of protection to allow fine-grained

over the visibility of variables and methods within classes, subclasses,and packages.
control
and containing the name space
Classes and packages are both means of encapsulating
act as containers for classes and other
and scope of variables and methods. Packages
for dataand code. The class is Java's
subordinate packages. Classes act as containers
Because of the interplaybetween classes and packages,
Java
smallest unit of abstraction.
for class members:
addresses four categories of visibility

Subclasses in the same package


• Non-subclasses in the same package
• Subclasses in different packages
Classes that are neither in the same package nor subclasses

The three access specifiers, private,public, and protected, provide a variety of ways
toproduce the many levels of access required by these [Link] 9-1 sums up the
interactions.

While Java's access control mechanismmay seem complicated, we can simplify


it as

follows. Anything declared public can be accessed from anywhere. Anything declared
does not have an explicit access
prívate cannot be seen outside of its class. When a member
187
Chapter 9: Packages and Interfaces

TABLE 9-1 Protected Public


Private No Modifier
Class Member
Yes Yes
Access Same class Yes Yes
Yes Yes
Same No Yes
package PARTI

subclass
Yes Yes
Same No Yes

package
non-subclass

No No Yes Yes
Different

package
subclass

No No No Yes
Different

package
|non-subclass

specification, it is visible to subclasses other classes in the same package. This is


as well as to

If you want to allow an element to be seen outside your current


package,
the default access.
that subclass your class directly, then declare that element protected.
but only to classes
has only two possible
Table 9-1 applies only to members of classes. A non-nested class
access levels: default and [Link] a class is declared as public,
it is accessible by any
has default then it can only be accessed by other code within its
other code. If a class access,
class declared in the file,
same package. When a class is public,it must be the only public
and the file must have the samne name as the class.

An Access Example
The following example showsall combinations of the access control modifiers. This example
has two packages and five classes. Remember that the classes for the two
different

packages-in
packages need to be stored in directories named after their respective
this

case, p1 and p2.


Derived, and SamePackage.
The source for the first package defines three classes: Protection,

The first class defines four int variables in each of the legal protectionmnodes. The variable n

is declared with the default protection, n_pri is private, n _pro is protected, and n_pub is
public.
Each subsequent class in this example will try to access the variables in an instance

of this class. The lines that will not compile due to access restrictions are commented out.
Before each of these lines is a commentlisting the places from which this level of protection
would allow access.
The second class, Derived, is asubclass of Protection in the same package, [Link]
grants Derived access to every variable in Protection except for n_pri, the private one. The
third class, SamePackage, is not a subclass of Protection,but is in the same package and
also has access to all but n_pri.
188 Part I: The Java Language

This is file [Link]:

package pl;

public class Protection


int n = l;
private int n pri = 2;
protected int n pro = 3;
public int n pub = 4;

public Protection () {
System. [Link]("base constructor");
[Link] ("n = " + n) ;
[Link]( "n pri = " + n pri);
System,[Link] ("n pro = " + n pro);
System. [Link] ("n pub = " + n pub);

This is file [Link]:

package pl;

class Derived extends Protection{


Derived () {
System. [Link]("derived constructor")
i
System. out .println("n = + n);
1/ class only
System. [Link] ("n pri = "4 + n pri) ;
System. [Link] ("n pro =" + n pro);
System. [Link] ("n pub = " + n pub) :

This is file [Link]:

package pl;

class SamePackage.
Same Package () {

Protection p = new Protection()


;
System. [Link] ("same package
constructor");
System. [Link] ("n = + p.n) "
;
class only
System. [Link] ("n pri = " + p.n pri);
System. [Link] ("n pro = "+ p.n pro);
[Link] ("n pub = "+ p.n pub) ;
Packages and Interfaces 189
Chapter 9:

Following is the source code for the other package, p2. The two classes defined in p2
COver the other twO conditions that are affected by access control. The first class, Protection2, is

[Link] grants access to all of [Link]'s variables except for


a subclass of
Remember,
npri (because it is private) arnd n, the variable declared with the default
protection.
PARTI
the default only allows access from within the class or the package, not extra-package

subclasses. Finally, the class OtherPackage has access to only one variable, n_pub, which
was declared public.
This is file [Link]:

package p2:

class Protection2 extends pl. Protection {


Protection2()
{
System. [Link] ("derived other package constructor") ;

1/ class or package only


// [Link] ("n = " + n);

class only
// [Link] ("n pri " + n pri) ;

System. [Link] ("n pro = " + n pro);


System. [Link] ("n pub = n + n pub) ;

This is file [Link]:

package p2;

class OtherPackage
OtherPackage () {
p1. Protection p = new [Link] ();
[Link]("other package constructor") ;

class or package only


// [Link] ("n = " + p.n) ;

class only
1/ [Link] ("n pri = "+ p.n pri);

class, subclass or package only


// System. [Link] ("n pro = + " p.n pro):

System. [Link] ("n pub = " + p.n pub) ;


The Java Langu age
190 Part I:

two test files you can use. The one for


you wish to try these two packages, here are
If

package pl isshown here:

//Demo package pl.


package pl;

1/ Instant iate the various classes in pl.


public class Demo
public static void main(String args []) {

Protection obl = new Protection ();


Derived ob2 = new Derived() ;
SamePackage ob3 = new SamePackage ();

The test file for p2 is shownnext:

1/ Demo package p2.


package p2;

1/ Instant iate the various classes in p2.


public class Demo {
public static void main (String args [O) {
Protection2 obl = new Protection2 (0;
OtherPackage ob2 = new OtherPackage () ;

Importing Packages
Given that packages exist and are a good mechanism for compartmentalizing diverse classes
from each other, it is easy to see why allof the built-in Java classes are stored in packages.
There are no core Java classes in the unnamed default package; all of the standard classes
are stored in somenamed package. Since classes within packages must be fully qualified
with their name or names, it could become tedious to type in the long dot-separated
package
package path name for every class you want to use. For this reason,Java includes the import
statement to bring certain classes, or entire packages, into visibility. Once imported, a class

can be referred to directly, using only its name. The import statement is a convenience to
the programmer and is not technically needed to write a complete Java program. If you are
going to refer to a few dozen classes in your application, however, the import statement will
save a lot of typing.
In a Java source file, import statements occur immediately following the package
statement
(ifit exists) and before any class definitions. This is the general form of the

import pkg1[-pkg2]. (classname | ");

Here,pkg1 is the name of a top-level package, and pkg2 is the


import statement:

name of a subordinate
package inside the outer package separated by a dot (). There is no
practical limit on the
depth of a package hierarchy, except that imposed by the file system. Finally, you specify
Chapter 9: Packages and Interfaces 191

either an classname or a star (),


explicit which indicates that the Java compiler should import
the entire package. This code fragment shows
both forms in use:
import [Link]. Date;
import [Link].*;

PAREE
CAUTION The forn mavy increase compilation
star
time--especially if you import several large
packages. For this reason itisagood idea to explicitly name the classes that you want to use
rather than importing whole packages. However, the star form has absolutely no effect on the
run-time performanceor size of your classes.

All of the standard Java classes included with Java are stored in a package called java.

The basic language functions are stored in a package inside of the java package called

[Link], you have to import every package or cdass that you want to use,but
since Java is uselesswithout much of the functionality in [Link], it is implicitly imported
by the compiler for all programs. This is equivalent to the following line being at the top of
all of your programs:

import [Link].*;

Ifa class with the same name exists in two different packages that you import using the
star form, the compiler will remain silent, unless you try to use one of the classes. In that case,
you get a compile-time error and have to explicitly name the class specifyingits package.
will

must be emphasized
It that the import statement is optional. Any place you use a class
name,you can use its fullyqualified name, which includes its full package hierarchy. For
example, this fragment uses an import statement:

import [Link] .*;


class MyDate extends Date {

The same example without the import statement looks like this:

class MyDate extends java. [Link]

In this version, Date is fully-qualified.

As shown in
Table 9-1, when a package is imported, only those items within the package
declared as public will be available to non-subclasses in the importing code. For example,
if you want the Balance class of the package MyPack shown earlier to be available as a

stand-alone class for general use outside of MyPack, then you will need todeclare it as
publicand put it into its own file, as shown here:

package MyPack;

/* Now, the Balance class, its constructor, and its


show () method are public. This means that they can
be used by non-subclass code outside their package.
*/
public class Balance {
192 Part I: The Java Langu age

String name;
double bal;

public Balance (String n, double b) {

name = n;
bal = b;

public void show () {

if (bal<0)
System. [Link] ("- -> ");
System. [Link] (name + ": $" + bal) ;

As you can see, the Balance class is now public. Also, its constructor and its show()
method are public, too. This means that they can be accessed by any type of code outside
the MyPack [Link] example, here TestBalance imports MyPack and is then able to
make use of the Balance class:

import MyPack. *;

class TestBalance
public static void main (String args []){
/* Because Balance is public, you may use Balance
class and call its constructor. */
Balance test = new Balance ("J. J. Jaspers", 99.88) ;
[Link] (); // you may also call show ()

Asan experiment, remove the public specifier from the Balance class and then try

compiling TestBalance. As explained, errors will result.

Common questions

Powered by AI

Within the same package, the 'protected' access modifier in Java allows class members to be accessed freely by any other class within the same package or by subclasses within the same package. Across different packages, 'protected' members can only be accessed by subclass objects. This ensures that while 'protected' provides more accessibility than 'private', it still safeguards class internals from unrestricted external access, reinforcing encapsulation while permitting necessary visibility to subclasses .

To compile and run a Java program using a custom package, first ensure the .java source files include a package statement that reflects the directory structure, e.g., 'package MyPack;'. Place the .java files in the appropriate directory, then compile using 'javac' from the directory above 'MyPack'. All class files should reside in the 'MyPack' directory after compilation. Set the CLASSPATH environment variable to include the path above 'MyPack', or use the '-classpath' option when running the program with 'java', e.g., 'java MyPack.AccountBalance'. The CLASSPATH is critical as it tells the Java runtime where to look for classes, and it must not include the package directory itself, only its path .

Java access specifiers control the visibility of class members, allowing for fine-grained access control across classes and packages. The 'public' specifier makes a member accessible from anywhere, 'private' restricts access to within its own class, and 'protected' allows access to subclasses and classes within the same package. Default access, which occurs without any specifier, limits access to the package. These access modifiers prevent data encapsulation breaches and enable secure data handling while permitting necessary sharing of members across related classes. These controls are essential for both internal class security and the integrity of data when interacting with external packages .

Default access in Java, without any specifier, limits accessibility to classes within the same package. This contrasts with 'private', which restricts access to within the class itself, and 'public', which allows access from any package. Default is useful for package-private components where internal package structure needs interaction without exposing to external packages. Use 'private' for internal logic security and 'public' for elements meant to be accessible outside their native package, balancing external accessibility with internal encapsulation .

To create a hierarchy of packages, separate package names with periods, for example, 'package com.example.project;'. This structure must be mirrored in the file system, meaning the directory structure should be '.../com/example/project/'. The CLASSPATH should point to the root directory of the package hierarchy, e.g., the directory above 'com'. This setup allows Java classes to access packages and subpackages conveniently. Proper hierarchy and classpath setup ensure that the intended scope and access levels are maintained across projects, facilitating modularity and manageability in larger systems .

To expose a class and its methods from a package, declare the class and its significant methods as 'public'. ```java package MyPack; public class Balance { String name; double bal; public Balance(String n, double b) { name = n; bal = b; } public void show() { if (bal < 0) System.out.print("--> "); System.out.println(name + ": $" + bal); } } ``` With this setup, the class 'Balance', its constructor, and 'show()' method are accessible to any non-subclass code outside their package. Import this package using 'import MyPack.*;' to use 'Balance' in another package .

A public class must be placed in a file named after the class to maintain consistency in the file-system, enabling the Java compiler to locate the correct source and compiled classes. This requirement ensures that when Java applications are compiled, the package and its classes are logically organized and accessible, aligning physical storage with program architecture. This structure supports navigability and systematic compilation processes, essential for maintaining program integrity and reducing compile-time errors .

The import statement simplifies code by avoiding the need to fully qualify class names, allowing direct reference to class names. Using 'import package.*;' imports all public classes in a package, which can save typing but might increase compilation time, especially with large packages, and can lead to naming conflicts if classes with the same names exist in different imported packages. However, importing entire packages has no impact on runtime performance. Care must be taken to explicitly name classes to prevent ambiguity, especially in large projects where dependencies are complex and numerous .

Java uses the file system to organize packages by mirroring package names with directories. For instance, if you declare a package as 'package MyPackage;', then all class files for that package must be stored in a directory called 'MyPackage'. Case sensitivity is crucial, as directory names must match package names exactly. This organizational structure implies that if you change the package name, you must also change the directory name to maintain consistency. A hierarchy of packages can be created by separating package names with a period, which must be reflected in the file system layout, e.g., 'package java.awt.image;' corresponds to 'java\awt\image' in Windows. This system ensures that the Java runtime can find and load classes correctly, provided the directory structure is adhered to .

Declaring a class as public means it can be accessed from outside its package, enabling its use in any package across a Java application. Public classes provide essential points of interaction with other code, but must be managed carefully to protect internal logic and data. The class must be in a file with the same name as the class to maintain file-system consistency. Public classes enable modular program design, but overexposure can lead to tight coupling and security risks if sensitive data or methods are not adequately protected .

You might also like