(syllabus and calendar)

Ch. 8. Packages and Interfaces

lecture8-2010b.zip

Session 8

Interfaces - more abstract than abstract classes


Packages


Reflection package


Jar instructions


Quiz

Interfaces - 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/

java.awt.event
Interface ActionListener

All Superinterfaces:
EventListener [A tagging interface that all event listener interfaces must extend. Does not specify any methods or properties.]
All Known Subinterfaces:
Action [has isEnabled property so you can disable both menu item and toolbar button that listen for the same event]
All Known Implementing Classes:
AbstractAction, AWTEventMulticaster, BasicOptionPaneUI.ButtonActionListener, BasicScrollBarUI.ScrollListener, BasicSliderUI.ScrollListener, BasicSplitPaneUI.KeyboardDownRightHandler, BasicSplitPaneUI.KeyboardEndHandler, BasicSplitPaneUI.KeyboardHomeHandler, BasicSplitPaneUI.KeyboardResizeToggleHandler, BasicSplitPaneUI.KeyboardUpLeftHandler, BasicTreeUI.ComponentHandler, DefaultCellEditor.EditorDelegate, DefaultTreeCellEditor, DropTarget.DropTargetAutoScroller, FormView, JComboBox, List.AccessibleAWTList, ToolTipManager.insideTimerAction, ToolTipManager.outsideTimerAction, ToolTipManager.stillInsideTimerAction

public interface ActionListener

extends EventListener

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.

actionPerformed

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

Defining an interface

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(); 

Implementing an interface

Abstract classes versus Interfaces: when to use which

  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,
that is, merely the capability
to have the flag.

(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
public interface Cloneable

A class implements the Cloneable interface to indicate to the Object.clone() method
that it is legal for that method to make a field-for-field copy of instances of that class.


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

Variables in Interfaces

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
   The "standard" output stream. This stream is already open and ready to accept output data.

For example:

----------

Combining an abstract class with an interface

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.


Extending an 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.

Creating and Implementing Interfaces

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.


Using Interface References (p. 320)

An interface reference variable accepts a reference to any object of any class that implements that interface.

Array element of interface type

An array element can store an object of any type that implements the interface type.

The output is:

Inventory@addbf1
Inventory@42e816
Inventory@9304b1

Method arg as interface type

A method's formal parameter that requires an interface type will accept a runtime argument of any class that implements the interface.

Interface as a type and inheritence

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?


Reflection package

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]



Packages

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.


Packages and Member Access

Package example: bicycle

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


Access Control: Summary

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

Package-level access control to Members of a Class: Four Levels

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
private X      
protected X X
limitation
X  
public X X X X
package X   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.

Public

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 Beta class one more time and put it in a different package than Alpha and 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, Beta can legally inspect and modify the iampublic variable in the Alpha class and can legally invoke publicMethod.

Private

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 private keyword 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 Alpha can inspect or modify the iamprivate variable and can invoke privateMethod, but objects of other types cannot.
For example, the Beta class defined here:

class Beta {
    void accessMethod() {
        Alpha a = new Alpha();
        a.iamprivate = 10;      // illegal
        a.privateMethod();      // illegal
    }
}

cannot access the iamprivate variable or invoke privateMethod on an object of type Alpha because Beta is not of type Alpha.

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 error

Also, 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 error

New Java programmers might ask if one Alpha object can access the private members of another Alpha object. This is illustrated by the following example. Suppose the Alpha class contained an instance method that compared the current Alpha object (this) to another object based on their iamprivate variables:

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: this is a Java language keyword that refers to the current object. For more information about how to use this see The Method Body.


Package

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 Alpha class declares a single package-access member variable and a single package-access method. Alpha lives in the Greek package:

package Greek;

class Alpha {
    int iampackage;
    void packageMethod() {
        System.out.println("packageMethod");
    }
}

The Alpha class has access both to iampackage and packageMethod. In addition, all the classes declared within the same package as Alpha also have access to iampackage and packageMethod. Suppose that both Alpha and Beta were declared as part of the Greek package:

package Greek;

class Beta {
    void accessMethod() {
        Alpha a = new Alpha();
        a.iampackage = 10;     // legal
        a.packageMethod();     // legal
    }
}

Beta can legally access iampackage and packageMethod as 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 the Alpha class, which is now declared to be within a package named Greek, 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 Gamma was also declared to be a member of the Greek package (and is not a subclass of Alpha).
The Gamma class can legally access an Alpha object's iamprotected member variable and can legally invoke its protectedMethod:

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 protected specifier affects access for subclasses of Alpha.

Let's introduce a new class, Delta, that derives from Alpha but lives in a different package--Latin. The Delta class can access both iamprotected and protectedMethod, but only on objects of type Delta or its subclasses. The Delta class cannot access iamprotected or protectedMethod on objects of type Alpha.
The Delta class has access to what Delta inherits as a subclass of Alpha, but Alpha is protected from encroachment by its subclass in a foreign package.
accessMethod
in the following code sample attempts to access the iamprotected member variable on an object of type Alpha, which is illegal, and on an object of type Delta, which is legal.
Similarly, accessMethod attempts to invoke an Alpha object's protectedMethod, 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.

 protected.zip


Creating a custom package

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 packages

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


Packing Java Itself

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.

Importing the classes of a package with the import keyword

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.

Finding the classes in a package

A package is both a library of functionality and a directory on the file system.

Declaring, Compiling, Running

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

CLASSPATH Alternative

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.


Controlling access and packages - review

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
(available to subclasses even if
they are outside the package with a
Limitation)
X X* X  
public (unrelated to packages) X X X X
package (default, not necessary to declare;
only classes in this package have access)
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.


Importing

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 in java.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:


Creating Packages

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 package statement 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 file Circle.java and puts the Circle class in the graphics package:

package graphics;

public class Circle extends Graphic implements Draggable {
    . . .
}

The Circle class is a public member of the graphics package.

You must include a package statement at the top of every source file that defines a class or an interface that is to be a member of the graphics package. So you would also include the statement in Rectangle.java and so on:

package graphics;

public class Rectangle extends Graphic implements Draggable {
    . . .
}

The scope of the package statement is the entire source file, so all classes and interfaces defined in Circle.java and Rectangle.java are also members of the graphics package. 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 package statement, 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.

Naming a Package

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 Rectangle class when there is already a Rectangle class in the java.awt package. 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 the Rectangle class in the graphics package is graphics.Rectangle, and the fully qualified name of the Rectangle class in the java.awt package is java.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 element com. 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 package statements).

Package Name

Class Name

mygame.server

Server

mygame.shared

Utilities

mygame.client

Client

a. 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.java add:
package mygame.client;
In Server.java add:
package mygame.server;:
In Utilities.java add:
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 the mygame directory, you need to create three subdirectories: client, server, and shared.

In mygame/client/ place:
Client.java
In mygame/server/ place:
Server.java
In mygame/shared/ place:
Utilities.java

c. 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.java and Server.java need to import the Utilities class, which they can do in one of two ways:

import mygame.shared.*;
import mygame.shared.Utilities;

Implementing an Interface in a Package

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


Jar instructions

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

  1. Write a program (such as this week's homework) with multiple files, such as one file with the Interface and another file with class that implements the interface.
    Make sure these files are in their own directory, because your jar will have all the files of that directory.
     
  2. Write a "manifest" file. This is a text file that tells the JVM which class in the JAR has the main method.
    The manifest file contains two line because it must end with a blank line.
    For example,

    Line 1: Main-Class: PackageDemo
    Line 2:

    Except that Line 2 would not have characters, not even "Line 2".


     
  3. Remember the exact name of the manifest file, including case and whether it has an extension, such as .txt or not.

    Note: Because the manifest tells the JVM which class is the main class, it is not necessary to have a file with the same name as the main class. For example, HelloWorld.class could be executed without having a HelloWorld.java file name. Typically, in addition to the manifest file, the jar zips up bytecode files, not source code files.
     
  4. Create the executable jar at the command line.
    For example,
    jar cmf myManifestForTheClassWithMain.txt myJarFile.jar *.*
    where
  1. Test the executable jar.

    To get a listing of the contents:
    jar tf myJarFile.jar

    To run the executable jar:
    java -jar myJarFile.jar

         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

  1. Email the executable jar to the instructor.

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


Quiz - Session 8

  1. How do you make a class belong to a specific package?

  2. What convention does Sun recommend to ensure that Oracle's packages for database functionality do not conflict with those of IBM?

  3. If your program is going to make many calls to three uniquely named classes that belong to three different packages, what would make writing your code more convenient?

  4. Suppose that the subclass whose members you want to call belongs to a different package. Is that a problem if the class is declared:

  1. What is the difference between an abstract class and an interface in terms of

  2. Does a class that implements an interface need to observe both method names and method signatures?

  3. To implement the Serializable interface, how many methods must a class implement?

  4. How many interfaces can a class implement?

  5. How many interfaces can a subinterface extend?

  6. If a method takes an argument of type Serializable, will it accept an argument of a type that represents a class that implements the Serializable interface?