|
Ch. 8. Packages and Interfaces |
Session 8Interfaces - more abstract than abstract classes
|
Last week we look at abstract classes. Tonight we look at something even more abstract: interfaces.
An abstract class should have one or more abstract methods.
An abstract method is a template for defining a method. It
specifies the parameter signature and the return type. Nothing more.
An abstract class permits partial implementation at its level, and requires complete implementation at the subclass level(s).
But what if we have no default implementation to provide? Perhaps we would want something more abstract than an abstract class. An interface is more abstract than an abstract class because an interface prohibits--at its level--implementation, even partial implementation.
Unified Modeling Language (UML) diagram of this conceptual distinction.

Let's summarize:
Here is a diagram showing how an interface can be part of a larger picture.

Interfaces, for purposes of design, avoid the constraint of single
inheritance. A class can implement zero, 1, or many interfaces.
A public interface must be in a .java file with its name, for example,
ISeries.java
Note: The convention of beginning an interface name with the capital letter "I" is a good one, although coders do not always observe it.

The class that uses the interface does the compilation. There will be a bytecode file with the normal extension called ISeries.class becase .class is the extension for bytecode. However, ISeries is NOT a class, and its bytecode has no point of entry for execution.
Note the keyword implements, which signals the compiler that this class follows the specifications of the ISeries interface.

TIP: Assuming the ISeries.java file is in the same directory, you do not have to compile it. The compiler follows the reference to ISeries and does the compilation for you.

A Java interface can be used in two kinds of scenarios, and they are as least as different as the + operator being used both for addition and concatenation.
EXAMPLE OF JAVA API INTERFACE
The ActionListener interface specifies one signature for one method.
http://java.sun.com/j2se/1.4.2/docs/api/
public interface ActionListener
The listener interface for receiving action events. The class that is
interested in processing an action event implements this interface, and the
object created with that class is registered with a component, using the
component's addActionListener method. When the action event occurs,
that object's actionPerformed method is invoked.
public void actionPerformed(ActionEvent e)Invoked when an action occurs.
Note: An interface supports polymorphism because it leaves to classes the implementation, and different classes can implement the same interface in different ways. However, polymorphism is usually refers to the ability to overload methods. An interface cannot provide any form of implementation, and the interface might be implemented by many, one, or zero classes.
Whereas a class can only inherit from one superclass (even if the class hierarchy creates a multi-level vertical chain), a class can implement multiple interfaces.
Interfaces provide an alternate route to specifying functionality without breaking the principle of single inheritance. The price is that functionality is merely specified, not implemented. The benefit of preserving single inheritance is that debugging only has to follow one line of inheritance, the single-parent chain of inheritance. Implementing one or more interfaces might lead to the realization that poor design has occurred, but an interface cannot cause a "bug" insofar as an interface has no runnable code. Every bug that needs to debugging can be worked on along a single path of inheritance.
An interface, like a class, is a type. A class that implements an interface can create objects that can pass for the type of the interface. Last week, with an abstract class, we saw "Dynamic Method Dispatch" ( http://write-technical.com/126581/session7/session7.htm#dispatch ) with resolution at runtime. Such type resolution can also work with classes that implement one or more interfaces. In this sense, an object is the type of ALL its inherited superclasses and ALL its implemented interfaces.
When you define an interface, you specify required methods and/or variables for whatever classes implement your interface, but you do not fill in method code blocks, that is, you do not implement.
interface MyInterface {
void myMethodX(double myParameter);
boolean myMethodY();
| CLASS | ABSTRACT CLASS | INTERFACE | |
| Definition: | A class must be complete, at least in form, or the compiler does not compile. Default behavior is not required but is generally the case. | An incomplete specification, which can provide default behavior. | A specification of behavior (methods) without any implementation (no default behavior) and no fields except for constants that are static and final. No method bodies. In effect, an interface is an application programming interface (API) with implicitly public methods. |
| Inheritance: | A class can extend only ONE class. A class inherits from its parent class (single inheritence), but can implement multiple interfaces. | A class can extend only ONE class, whether it is
abstract or not. The class that extends its abstract class parent can implement some methods and declare other methods to be abstract (for still later implementation) |
A interface can be implemented by zero, one, or more
classes.
An interface can extend zero, one, or more superinterfaces. The class that implements an interface must implement all interface methods and any superinterface methods. |
| When to create: | Create a class if you know the default behavior you want, and if you do not need to provide a specification for other programmers. | Create an abstract class if you
want to partially implement a class now, and have you or others do
additional implementation later. Subclasses can benefit from the default implementation of (some) methods of the abstract class. API Flexibility: An abstract class allows you to add nonabstract methods without breaking classes that extend the abstract classes. |
Create an interface if (1) you want to define methods
(no current implementation at all) that you,
or others, will later implement, and (2) you want a workaround for the
absence of "multiple inherence" (C++ "mixins). |
| Create an interface if you want a convenient way for any class to have access to a set of constants. In this case, your interface would not contain any methods. | |||
| Create an interface if you want a commitment to stability and to impose a set of considerations for design: because an interface is an API, you cannot add any new methods without breaking any classes that implement the previous version. |
EXAMPLE


The output is:
Implement getMeat() method from interface
ICarnivore.
Implement huntMethod(), from interface IFeline. For a cat, waiting next to the f
ood dish might count as hunting?
Cat extends MamalClass, so it must have a giveMilk method.
Abstract superclass AbstractAnimal implements this concrete eating method by ext
racting oxygen from the environment. A Fish class can override this method to ge
t oxygen exclusively from water. A non-Fish class can override to get oxygen exc
lusively from the atmosphere. An Amphibious might get oxygen from both air and w
ater?
Subclass MammalClass implements ProtectFromCold by growing hair. All mammals hav
e hair.
|
An interface can be devoid of
content. Such interfaces do not require the implementation of any method.
They function as flags that indicate a capability.
That capability can be empty, (What capability is guaranteed when someone waves the flag at a parade? Nothing but the signal itself.) |
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Cloneable.html
A class implements the http://java.sun.com/j2se/1.4.2/docs/api/ java.io.Serializable Indicates support for moving not just data but objects across a network. http://java.sun.com/docs/books/tutorial/essential/io/serialization.html |
Most often, one finds methods in an interface. An interface specifies class members independent from, and prior to, any implementation or instantiation. Interface variables are a way to ensure that all objects of that type have pre-initialized variable values. (The other way is the implicit call to the superclass, which can initialize inherited values. But that will affect performance.) Therefore, an interface can also provide static variables because static variables exist prior to and independently of any implementation or instantiation of objects:
For example, we often write System.out.println("HelloWorld");
which uses something static so that print to the screen even before we instantiate any object.
public static final PrintStream out
For example:
![]()
----------
What if you only want to implement some (but not all) of the classes in the interface?
In this case, the implementing class must be declared an
abstract class with the modifier
abstract. The duty of
implementation must be fulfilled by whatever class extends the abstract class.
Neither an abstract class or
an interface can be instantiated. The implement is either a subclass of the
abstract class or an class that implements all the methods the interface.

The Serializable interface has many subinterfaces: http://download.oracle.com/javase/6/docs/api/java/io/Serializable.html
Some of these subinterfaces have their own subinterfaces: http://download.oracle.com/javase/6/docs/api/java/security/PublicKey.html
One use case for extending interfaces is to perform something a bit similar to multiple inheritance. A subinterface called Dog might inherit the contract for getName() and bark(). However, there is no need to support the renaming of a dog object. The subinterface called MutableDog might also inherit the setName() contract. The application that implements the MutableDog interface has to provide a code block for each of three methods, including support for the renaming of a dog object.

Another example: the IReplacableByPatron subinterface for a library might extend both the ILibraryProperty interface and the IDonor interface. In this scenario, normally if a patron loses a library item, the patron must eventually pay the library to order a replacement item, which might be slow, expensive (many publications cost ten times more for a library to order than for a single person to order), and require the involvement of a remote billing department. If instead, the patron chooses to quickly locate and donate the item, the library can get the item back in circulation quicker and cheaper. The library can use the IDonor interface to avoid charging the patron a fine.

You already know that you can write a subclass that inherits from its
superclass by using the keyword extends.
Similarly, you can write an interface that inherits from an existing interface,
and the keyword remains extends.
http://java.sun.com/docs/books/tutorial/java/interpack/interfaces.html
The Java programming language supports interfaces that you use to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy.
- What Is an Interface?
- This section defines the term "interface," shows you an example of an interface and how to use it, and talks about why you may need interfaces in your programs.
- Defining an Interface
- Defining an interface is similar to creating a new class. An interface definition has two components: the interface declaration and the interface body.
interfaceDeclaration { interfaceBody }The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceBody contains the constant and method declarations within the interface.
- Implementing an Interface
- To use an interface, you write a class that implements the interface. When a class claims to implement an interface, the class is claiming that it provides a method implementation for all of the methods declared within the interface (and its superinterfaces).
- Using an Interface as a Type
- When you define a new interface you are in essence defining a new reference data type. You can use interface names anywhere you'd use any other type name: variable declarations, method parameters and so on.
- Warning! Interfaces Cannot Grow
- If you ship public interfaces to other programmers, here's a limitation of interfaces that you should be aware of: Interfaces cannot grow. Let's look at why this is the case.
- Summary
- A summary of important concepts covered in this section.
http://java.sun.com/docs/books/tutorial/java/interpack/QandE/interfaces-answers.html
Question 1: What methods would a class that
implements the java.util.Iterator interface have to implement?
Answer 1: next, hasNext,
and remove
Question 2: What is wrong with the following interface?
public interface SomethingIsWrong {
public void aMethod(int aValue) {
System.out.println("Hi Mom");
}
}
Answer 2: It has a method implementation in it. It should just have a declaration.
Question 3: Fix the interface in Question 2.
Answer 3:
public interface SomethingIsWrong {
public void aMethod(int aValue);
}
Question 4: Is the following interface valid?
public interface Marker {
}
Answer 4: Yes. Methods are not required. Empty
interfaces can be used as types and to mark classes without requiring any
particular method implementations. For an example of a useful empty interface,
see java.io.Serializable.
The serialization interface has no methods or fields and serves only to identify
the semantics of being serializable.
An interface reference variable accepts a reference to any object of any class that implements that interface.
An array element can store an object of any type that implements the interface type.

The output is:
Inventory@addbf1
Inventory@42e816
Inventory@9304b1
A method's formal parameter that requires an interface type will accept a runtime argument of any class that implements the interface.

An interface is a type, just as a class is a type.



Another example. How does line 56 relate to lines 59 and 62? Does the interface reference variable, ob, know about methods and variables specific to the classes that implement the interface?


The Java APIs provide an empty interface for serialization. Serialization means to take apart an object, move it over the network (or onto disk), then put it back again. Serialization relies on reflection, as does the inheritance hierarchy shown in the javadoc for the Java's API. Reflection is an advanced topic, so this is just a brief introduction to a general concept. Reflection is about meta-data, that is, code about code rather than about solving problems in a specific domain.
http://java.sun.com/javase/6/docs/api/java/lang/reflect/package-tree.html

This example uses the reflection package to return information about about a class, such as its methods.

D:\__sessions07Spring\learn-java\examples\ch07>java Invoke java.util.Calendar ge
tInstance
The output is:
Invoked static method: getInstance of class:
java.util.Calendar with no args
Results: java.util.GregorianCalendar[time=1171695466071,areFieldsSet=true,areAll
FieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="America/Los_Ange
les",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRu
le=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3
600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDay
OfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDay
OfWeek=1,endTime=7200000,endTimeMode=0]],firstDayOfWeek=1,minimalDaysInFirstWeek
=1,ERA=1,YEAR=2007,MONTH=1,WEEK_OF_YEAR=7,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF
_YEAR=47,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=10,HOUR_OF_DAY=22,MIN
UTE=57,SECOND=46,MILLISECOND=71,ZONE_OFFSET=-28800000,DST_OFFSET=0]
Recall that packages organize the Java application programming interface:

A package is a set of related classes.
java.util is a package that comes with the
SDK (see
http://java.sun.com/javase/6/docs/api/java/util/package-summary.html). Among
the utilities in this package is the Calendar class:
http://java.sun.com/javase/6/docs/api/java/util/Calendar.html, which
provides "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." A class
can import a package, which gives the coder easy access to the classes in the
package.


Lets begin with an example.

PackageDemo will import the bicycle package. A subdirectory named bicycle contains an interface, and two classes that implement the interface. The interface and two classes belong to a package with the same name as the subdirectory. Because the DirtBike and RoadBike classes implement the IVehicle interface (or any interface), both classes must be declared public. In addition, the PackageDemo class can only call the methods within DirtBike and RoadBike if those methods are also declared public.
A class or interface that belongs to a package must declare the package as the first line of code.



The demo class imports the package.

A zip of this code and file structure: packagedemo.zip with the password package
Note that a reference of the type of the implemented interface type can dynamically refer to an object of either class that does the implementation (lines 11 and 15).

In Week 7, we learned about access control at the class level. A class member can be declared public or private. This is a good kind of encapsulation, but this encapsulation can itself be encapsulated within package-level encapsulation, because a package contains one or more classes. To make an analogy with Russian dolls, some John Lennon fans consider that John's overarching talent is the container for Paul's creativity, even if Paul can up with the idea of bringing George into the Beatles and sometimes directed George's strumming and picking. Finally, even Ringo himself admitted that, in terms of musical inventiveness, he was last and least of the Fab Four and merely pounded the drums as he was told to do. If a journalist wanted to know the history of the Beatles or a Beatles song, the best bet would have been to ask John, who more than the others encapsulated and controlled what the Beatles were about.

What can be made private? How about an entire class? No. A private class would allow no access and would be useless. There are only two access levels for a class: public or the nameless default, which is accessible within the package (the current directory).
If you declare a class to be public:
| Class Specifier | within the package | outside the package |
|---|---|---|
public |
X | X |
default (undeclared) |
X |
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
Encapsulation: One of the benefits of classes is that classes can protect their member variables and methods from access by other objects. Why is this important? Well, consider this. You're writing a class that represents a query on a database that contains all kinds of secret information, say employee records or income statements for your startup company.
Certain information and queries contained in the class, the ones supported by the publicly accessible methods and variables in your query object, are OK for the consumption of any other object in the system. Other queries contained in the class support the operation of the class--such as an "internal engine"--but should not be used by objects of another type. You want to protect secret information from, say, programmers in other departments in your company. Or, you want to keep your program stable while third parties make calls into your code using application programming interfaces (API calls) you expose. Suppose you a providing a web service and want other programmers to make use its public aspects only. One scenario might be the U.S. Post Office encouraging a zip code look-up service to be integrated with the software on cell phones.
In Java, you can use access specifiers to protect both class variables and methods. You use the access specifier as part of your declaration.
The Java language supports four distinct access levels for member variables and methods: private, protected, public, and, if left unspecified, package.The following chart shows the access level permitted by each specifier.
Class Member Specifier class subclass package world privateX protectedX X
limitationX publicX X X X packageX X The class column indicates whether the class itself has access to the member defined by the access specifier.
A class always has access to its own members.
The subclass column indicates whether subclasses of the class (regardless of which package they are in) have access to the member.
The package column indicates whether classes in the same package as the class (regardless of their parentage) have access to the member.
The world column indicates whether all classes have access to the member.
The easiest access specifier is
public. Any class, in any package, has access to a class's public members. Declare public members only if such access cannot produce undesirable results if an outsider uses them.To declare a public member, use the keyword
public. For example,package Greek; public class Alpha { public int iampublic; public void publicMethod() { System.out.println("publicMethod"); } }Let's rewrite our
Betaclass one more time and put it in a different package thanAlphaand make sure that it is completely unrelated to (not a subclass of)Alpha:package Roman; import Greek.*; class Beta { void accessMethod() { Alpha a = new Alpha(); a.iampublic = 10; // legal a.publicMethod(); // legal } }As you can see from the above code snippet,
Betacan legally inspect and modify theiampublicvariable in theAlphaclass and can legally invokepublicMethod.
The most restrictive access level is private. A private member is accessible only to the class in which it is defined. Use this access to declare members that should only be used by the class. This includes variables that contain information that if accessed by an outsider could put the object in an inconsistent state, or methods that, if invoked by an outsider, could jeopardize the state of the object or the program in which it's running.
To declare a private member, use the
privatekeyword in its declaration. The following class contains one private member variable and one private method:class Alpha { private int iamprivate; private void privateMethod() { System.out.println("privateMethod"); } }Objects of type
Alphacan inspect or modify theiamprivatevariable and can invokeprivateMethod, but objects of other types cannot.
For example, theBetaclass defined here:class Beta { void accessMethod() { Alpha a = new Alpha(); a.iamprivate = 10; // illegal a.privateMethod(); // illegal } }cannot access the
iamprivatevariable or invokeprivateMethodon an object of typeAlphabecauseBetais not of typeAlpha.When one of your classes is attempting to access a member variable to which it does not have access, the compiler prints an error message similar to the following and refuses to compile your program:
Beta.java:9: Variable iamprivate in class Alpha not accessible from class Beta. a.iamprivate = 10; // illegal ^ 1 errorAlso, if your program is attempting to access a method to which it does not have access, you will see a compiler error like this:
Beta.java:12: No method matching privateMethod() found in class Alpha. a.privateMethod(); // illegal 1 errorNew Java programmers might ask if one
Alphaobject can access the private members of anotherAlphaobject. This is illustrated by the following example. Suppose theAlphaclass contained an instance method that compared the currentAlphaobject (this) to another object based on theiriamprivatevariables:class Alpha { private int iamprivate; boolean isEqualTo(Alpha anotherAlpha) { if (this.iamprivate == anotherAlpha.iamprivate) return true; else return false; } }This is perfectly legal. Objects of the same type have access to one another's private members. This is because access restrictions apply at the class or type level (all instances of a class) rather than at the object level (this particular instance of a class).
Note:
thisis a Java language keyword that refers to the current object. For more information about how to usethissee The Method Body.
The package access level is what you get if you don't explicitly set a member's access to one of the other levels.
The package access level allows classes in the same package as your class to access the members.
The existence of inheritance outside the package does not grant access: subclasses that are not in the package do not have access.
Package trust is like that which you extend to your "pack" of friends in the dormitory but wouldn't entrust to others based on inheritance (children or parents who are not part of our household).For example, this version of the
Alphaclass declares a single package-access member variable and a single package-access method.Alphalives in theGreekpackage:package Greek; class Alpha { int iampackage; void packageMethod() { System.out.println("packageMethod"); } }The
Alphaclass has access both toiampackageandpackageMethod. In addition, all the classes declared within the same package as Alpha also have access toiampackageandpackageMethod. Suppose that bothAlphaandBetawere declared as part of theGreekpackage:package Greek; class Beta { void accessMethod() { Alpha a = new Alpha(); a.iampackage = 10; // legal a.packageMethod(); // legal } }
Betacan legally accessiampackageandpackageMethodas shown.
Protected protects members from other packages
Protected access means the members of all the following have access:
Use the protected access level when it's appropriate for a class's subclasses to have access to the member, but not unrelated classes.
In this example, we protect the title of a Book from classes in other packages unless that class in another package is a subclass of Book.
The file, Book.java, resides in a directory named BookPack.
The files, ExtBook.java and ProtectDemo.java, resides in a directory named BookPackB.
The ExtBook class is in a foreign package, yet it has direct access to protected fields of Book because it is a subclass of Book.
However, the class with main is NOT a subclass of Book, and it resides in a foreign package. Therefore line 22 is illegal. The Book class is protected from foreign classes and does not need protection from its own subclasses.
To compile, start the command-line one directory above the package directories, so you can specify the package directory of the class with main:
java BookPackB/ProtectDemo
To run, keep the command-line one directory above the packages, so you can specify the fully-qualified name of the class with main:
java BookPackB.ProtectDemo
Another example ...
Protected members are like family secrets--you don't mind if the whole family knows, even those who live far away, and that you also trust to a few close friends.To declare a protected member, use the keyword
protected. First, let's look at how the protected specifier affects access for classes in the same package. Consider this version of theAlphaclass, which is now declared to be within a package namedGreek,and which has one protected member variable and one protected method declared in it:package Greek; public class Alpha { protected int iamprotected; protected void protectedMethod() { System.out.println("protectedMethod"); } }Now, suppose that the class
Gammawas also declared to be a member of theGreekpackage (and is not a subclass ofAlpha).
TheGammaclass can legally access anAlphaobject'siamprotectedmember variable and can legally invoke itsprotectedMethod:package Greek; class Gamma { void accessMethod() { Alpha a = new Alpha(); a.iamprotected = 10; // legal a.protectedMethod(); // legal } }That's pretty straightforward. Now, let's investigate how the
protectedspecifier affects access for subclasses ofAlpha.Let's introduce a new class,
Delta, that derives fromAlphabut lives in a different package--Latin. TheDeltaclass can access bothiamprotectedandprotectedMethod, but only on objects of typeDeltaor its subclasses. TheDeltaclass cannot accessiamprotectedorprotectedMethodon objects of typeAlpha.The
Deltaclass has access to whatDeltainherits as a subclass ofAlpha, butAlphais protected from encroachment by its subclass in a foreign package.in the following code sample attempts to access the
accessMethodiamprotectedmember variable on an object of typeAlpha, which is illegal, and on an object of typeDelta, which is legal.
Similarly,accessMethodattempts to invoke anAlphaobject'sprotectedMethod,which is also illegal:package Latin; import Greek.*; class Delta extends Alpha { void accessMethod(Alpha a, Delta d) { a.iamprotected = 10; // illegal d.iamprotected = 10; // legal a.protectedMethod(); // illegal d.protectedMethod(); // legal } }If a class is both a subclass of, and in the same package as, the class with the protected member, then the class has access to the protected member.
First, let's show the magic of a ready-to-run Java archive (JAR).
This jar contains the files of a package:
my-package-jar
To run the jar: java -jar my-package-jar
To see the contents:
jar tf my-package-jar
META-INF/
META-INF/MANIFEST.MF
AnimalPackageDemo.class
AnimalPackageDemo.java
animals/
animals/Beast.class
animals/Beast.java
animals/Dog.class
animals/Dog.java
animals/IAnimal.class
animals/IAnimal.java
my-manifest.txt
Navigate to one directory above the package.
This example shows that for compilation we refer to the file system ( / ) and
for execution to the class as part of a package ( . )
javac
BookPack/BookDemo.java
java BookPack.BookDemo

Navigate to one directory above the package. The following example runs a program that imports three packages:
D:\packages>javac
RunStuff.java
D:\packages>java RunStuff
Inside RunStuff
Can RunStuff instantiate MyStuffClass and call its callMe method?
Can RunStuff instantiate YourStuffClass and call its callMe method?
Can RunStuff instantiate OurStuffClass and call its callMe method?
This is greeting on an instance of Different class in the ourstuff package




The directory structure matches the packages by having folders for yourStuff, ourStuff, and myStuff:

We compile and run RunStuff.java from above the packages. Importing the packages in RunStuff.java points the compiler and the interpreter to the directories where the packaged files can be located.
Naming convention is lowercase, so the ourStuff package should be renamed to our_stuff.

http://java.sun.com/docs/books/tutorial/java/package/namingpkgs.html
Sun's presentation of the Java API begins with the packages, each of which groups together classes that provide an area of functionality.:
http://java.sun.com/j2se/1.4.2/docs/api/
| java.lang | Provides classes that are fundamental to the design of the Java programming language. |
| java.util | Contains the collections framework, event model, date and time facilities, internationalization, and a random-number generator, and others classes. |
| java.sql | Provides the API for accessing and processing data stored in a relational database. |
When you program with the Java APIs, you must import whatever package(s) we need to gain access to functionality beyond that of the default package, java.lang
When you import a package, the namespace of its classes are immediately visible to the compiler. You no longer need the fully qualified name. Therefore, typing the import keyword at the beginning can also save us typing later on.
The Java SKD provided many packages that you can import as you need them.
In addition, you can also create your own packages, and import them as you need
them.
If you name your classes in a consistent, indicative manner, and group your
classes into packages with indicative names, it makes it easier for users of
your classes to locate your classes.
For example, the classes in to a financial system might belong to two packages:
Accounting and Payroll.
A package is both a library of functionality and a directory on the file system.
This is an example of a custom package.
AccountBalance.class must reside in a directory named MyPack so that the Java interpreter can use the package statement to find the bytecode:
To compile: navigate one directory above the package directory and specify the relative path to the source code file.
To run: navigate one directory above the package directory and specify the fully-qualified class name (including package name prefix with dot (.)

Note: You can also use the relative path,
java MyPack/AccountBalance, because the file system and the package logic
correspond exactly.

Let's look at the source code.

What went wrong?
Two things.
(1) I need to change directories so that I am one level above the package.
(2) The command that invokes the interpreter to run the bytecode must be
include a reference to both the package and the class:
java MyPack.AccountBalance
or to both the package directory and the class:
java MyPack/AccountBalance

The interpreter accepts both the package directory and the package name because
the file system is organized such that packages and directories map to each
other.
To restate: the command line must reference the fully-qualified class name, that is, with the prefix for the package (or package directory).
Alternatively, you can update the classpath environment variable to point to the directory for the package, which product installers often do.
The following sets the classpath to the current directory and the root of the C drive. C:\>set CLASSPATH=.;C:\;
By convention, a company should name its packages by using its internet URL
in reverse as a prefix.
For example: com.mycompany.mypackage.
A class can have only two levels of access:
A class member (field or method) have can any of four levels of access:
Remember that the class is the feature of Java that supports encapsulation. Many methods and properties in a class can be hidden or private.
Most APIs expose public and protected members.

http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
| Specifier for class or members: | class | subclass | package | world |
|---|---|---|---|---|
private (unrelated to packages) |
X | |||
protected
Limitation) |
X | X* | X | |
public (unrelated to packages) |
X | X | X | X |
package (default, not necessary to declare; |
X | X |
The default access control is package does not require a keyword and means that MyClass is visible to its subclasses as well as to other classes in the same package.
A package is a grouping of classes in a directory. Therefore, there is no access control modifier on packages. For example, you can specify private for a class member but not for a package.
The keyword to import a package (so you do not need to use the fully-qualified name) is import and it should be at the top of the file. The syntax is:
import packagename.*;
where the wildcard * means to import all the classes of the package. You can specify specific classes, but why bother? (If you modify your code to work with a different set of classes in that package, you might create a maintenance problem.)
To import the classes in the java utility package, make the following the first statement of your .java file:
import java.util.*
http://java.sun.com/docs/books/tutorial/java/interpack/packages.html
To make classes easier to find and to use, to avoid naming conflicts, and to control access, programmers bundle groups of related classes and interfaces into packages.
Definition: A package is a collection of related classes and interfaces providing access protection and namespace management.
The classes and interfaces that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in
java.lang, classes for reading and writing (input and output) are injava.io, and so on. You can put your classes and interfaces in packages, too.Let's look at a set of classes and examine why you might want to put them in a package. Suppose that you write a group of classes that represent a collection of graphic objects, such as circles, rectangles, lines, and points. You also write an interface,
Draggable, that classes implement if they can be dragged with the mouse by the user://in the Graphic.java file public abstract class Graphic { . . . } //in the Circle.java file public class Circle extends Graphic implements Draggable { . . . } //in the Rectangle.java file public class Rectangle extends Graphic implements Draggable { . . . } //in the Draggable.java file public interface Draggable { . . . }You should bundle these classes and the interface in a package for several reasons:
- You and other programmers can easily determine that these classes and interfaces are related.
- You and other programmers know where to find classes and interfaces that provide graphics-related functions.
- The names of your classes wont conflict with class names in other packages, because the package creates a new namespace.
- You can allow classes within the package to have unrestricted access to one another yet still restrict access for classes outside the package.
http://java.sun.com/docs/books/tutorial/java/interpack/createpkgs.html
To create a package, you put a class or an interface in it. To do this, you put a
packagestatement at the top of the source file in which the class or the interface is defined. For example, the following code appears in the source fileCircle.javaand puts theCircleclass in thegraphicspackage:package graphics; public class Circle extends Graphic implements Draggable { . . . }The
Circleclass is a public member of thegraphicspackage.You must include a
packagestatement at the top of every source file that defines a class or an interface that is to be a member of thegraphicspackage. So you would also include the statement inRectangle.javaand so on:package graphics; public class Rectangle extends Graphic implements Draggable { . . . }The scope of the
packagestatement is the entire source file, so all classes and interfaces defined inCircle.javaandRectangle.javaare also members of thegraphicspackage. If you put multiple classes in a single source file, only one may be public, and it must share the name of the source files base name. Only public package members are accessible from outside the package.If you do not use a
packagestatement, your class or interface ends up in the default package, which is a package that has no name. Generally speaking, the default package is only for small or temporary applications or when you are just beginning development. Otherwise, classes and interfaces belong in named packages.
With programmers all over the world writing classes and interfaces using the Java programming language, it is likely that two programmers will use the same name for two different classes. In fact, the previous example does just that: It defines a
Rectangleclass when there is already aRectangleclass in thejava.awtpackage. Yet the compiler allows both classes to have the same name. Why? Because they are in different packages, and the fully qualified name of each class includes the package name. That is, the fully qualified name of theRectangleclass in thegraphicspackage isgraphics.Rectangle, and the fully qualified name of theRectangleclass in thejava.awtpackage isjava.awt.Rectangle.This generally works just fine unless two independent programmers use the same name for their packages. What prevents this problem? Convention.
By Convention: Companies use their reversed Internet domain name in their package names, like this:
com.company.package. Some companies now choose to drop the first elementcom.in this example from their package names. Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name, for example,com.company.region.package.
http://java.sun.com/docs/books/tutorial/java/interpack/QandE/packages-answers.html
Answers to Questions and Exercises: Creating and Using Packages
Question 1: Assume that you have written some classes. Belatedly, you decide that they should be split into three packages, as listed in the table below. Furthermore, assume that the classes are currently in the default package (they have no
packagestatements).
Package Name
Class Name
mygame.server
Server
mygame.shared
Utilities
mygame.client
Clienta. What line of code will you need to add to each source file to put each class in the right package?
Answer 1a: The first line of each file must specify the package:
- In
Client.javaadd:package mygame.client;- In
Server.javaadd:package mygame.server;:- In
Utilities.javaadd:package mygame.shared;b. To adhere to the directory structure, you will need to create some subdirectories in your development directory, and put source files in the correct subdirectories. What subdirectories must you create? Which subdirectory does each source file go in?
Answer 1b: Within themygamedirectory, you need to create three subdirectories:client,server, andshared.
- In
mygame/client/place:Client.java- In
mygame/server/place:Server.java- In
mygame/shared/place:Utilities.javac. Do you think you'll need to make any other changes to the source files to make them compile correctly? If so, what?
Answer 1c: Yes, you need to add import statements.Client.javaandServer.javaneed to import theUtilitiesclass, which they can do in one of two ways:import mygame.shared.*; import mygame.shared.Utilities;
Use this zip to have a template of classes in different directories that correspond to different packages. Note the use of the keyword "package, "public", and "import".
Write an Animal interface, implement it, create a package, and email the .zip




Here, the class with main is one directory above the animals subdirectory that holds the classes in the animals package. Therefore, we compile and run from the directory with that imports the package. We are already one directory above the package directory. This is the easiest way to do this week's homework.
D:\packages\test>javac AnimalPackageDemo.java
D:\packages\test>java AnimalPackageDemo
Inside AnimalPackageDemo
Beast roar
Dogs might fetch
An executable jar is a Java Archive, that is, a single file that contains multiple files. The archive generally contains .class files. (An installer might update the PATH so that the application can easily be run.) The archive can also be used to ship your homework (.java files).

- jar invokes the jar utility
- cmf means create a jar with the manifest file
- myManifestForTheClassWithMain.txt is the file discussed in Step 2 that indicates which class has the main method
- myJarFile.jar is the name of the jar (which normally ends in .jar to indicate that it is a jar file), and
- *.* means to include all the files in the current directory in the newly created jar.
Note that many software vendors ship their jar with the .class files but not the .java files. However, your instructor does want to see your source code. (We are doing open source development.)
To verify that its files can
be extracted to expose that files it contains: the manifest, the *.class files,
the *.java files:
jar xvf myJarFile.jar
However, this assignment is to email the instructor solely the .jar file,
not a .zip file. Remember, all that an installer program needs to deploy is
a single .jar file. The one jar file can be used to run all the functionality
involving multiple .class files in multiple directories. Typically, the
.jar
file would NOT be expanded, but I will expand your .jar file so I can examine
the manifest file and source code.
To run this Jar: java -jar myJarFile.jar
You can download this example of a jar.
If you run it with java -jar myJarFile.jar
The output is:
Dirt bike moves with large, heavy tires
Dirt bike stops quickly with metal disk brakes even in rain and mud
Road bike moves with thin, light tires for speed
Road bike not designed for rain and mud
because the jar contains the same code as that of package example: bicycle
public?
protected?
no access modifier specified?