(syllabus and calendar)

Ch. 8. Packages and Interfaces

week-8-examples-2011.zip

Session 8

Interfaces - more abstract than abstract classes


Packages


Reflection package


Jar instructions


Quiz


Hash table, a data structure

Review of Single Parent Inheritence and instanceof

Just as a child inherits a family name, so a subclass object is of the same type as its parent. However, the parent is NOT of the same type as its child. The instanceof operator allows you to test whether an object reference is of the type you need it to be.

In Java, the inheritance tree is single, not double. It is as if Barack Obama were an Obama through his father, but not a Dunham through his mother, Stanley Ann Dunham.

The advantage of single inheritance is simplicity, especially for debugging. We will see that the existence of interfaces cannot cause a "bug" insofar as an interface has no runnable code. Insofar as debugging a class that implements multiple interface is an operation carried out along a single path of inheritance, the existence of multiple interfaces does not complicate debugging. For example, a television, which implements both the IImage interface and the ISound interface, can have the sound fail while the picture still functions.

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.

The Java API link to "All Classes" should be labeled "All Classess and Interfaces" because it lists each interface in italics.

Unified Modeling Language (UML) diagram of the conceptual distinction between an implementing class and the interface or abstract class that dictates the signature to use when implementing.

Let's summarize:

Often, an interface represents a capability, such as ITaxable, IShippable, IReturnable, IBreakable, IPettable, ICarnivore, IClonable, ISerializable.

Analogies to illustrate the concept

The Declaration of Independence makes a claim akin to what Java calls in interface insofar as all "men" are implementations of the EqualityInCreation interface, and thereby have these behaviors or methods: areLiving(), haveLiberty(), pursueHappiness(), consentToBeGovernedIfTheGovernmentSecuresTheseRights(), and haveRightToRebelAgainstUnjustGovernment(). The interface is a blueprint only, and does not specify the exact behavior of specific "men".

In this regard, we can say that Jefferson's actions or behavior means he was an implementation of multiple interfaces, simultaneously an object of the following types:

(At that time in Paris, a 44-year old "white" diplomat in the pursuit of happiness getting his 16-year "black" old servant pregnant was not considered a scandal. However, to get Sally Hemings back on the farm after she'd seen Paris [where she could have remained free], Jefferson had to promise to reclassify both the mother and her children as "white" upon his death). http://en.wikipedia.org/wiki/Sally_Hemings

Here's an instance of RoboDog, which is a subclass of Robot. Unlike Robot, RoboDog implements the Pet interface, which specifies the requirement for a doTrickForOwner method.

Alternatively, we can imagine a bionic cyber-creation DogBot as a subclass of Dog, which might already have a doTrickForOwner method. Unlike Dog, DogBot implements the Robot interface, which specifies the requirement for an bootUpWhenSpinalButtonPressed method.

Here is a diagram showing how an interface can be part of a larger picture. The Factory class implements the IFactory interface by implementing the CreateProduct method, which, in turn, returns a ConcreteProduct, which is a specialized Product.

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 implements the interface can be instantiated.

Although an interface can be compile to a bytecode file, and the bytecode file has the normal extension .class, this is because .class is the extension for all bytecode the JVM considers. However, ISeries is NOT a class, and its bytecode has no point of entry for execution.

Whereas a subclass extends its superclass, with interfaces, the implementing class declares 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.

In this example, The ITaxable interface becomes tangible both in the company's on-hand inventory and the company's special order from a third-party for resale. The internal revenue service prefers than many classes be implementations of the ITaxable interface.

So, if you buy a basketball at a sporting good store, you by both an object of type Basketball and of type ITaxable, that is, a taxable item.

At a grocery store, a bottle of vodka object is of a class that implements ITaxable, but a carton of milk is not of ITaxable. Milk might be of ITaxExempt. Note that to be taxable, the Vodka class does not need to implement any method. The taxability of certain items is assigned in a manner that is external to the methods of the class. Some interfaces are a flag or signal rather than a set of implemented behaviors.


A Java interface can be used in three kinds of scenarios.

Interface as Marker - a Pattern


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.

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 as a signature and return value, but not implemented concretely.

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.  The thomas object is of type Instructor and its superclass HumanBeing but also of the interface IEvaluateable insofar as all instructors can be evaluated.

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 IDebatable 
{
  void stateSomethingNotFactual(double myParameter);
  boolean insistOnSomethingNotFactual();
} 

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 an application with classes that extend the abstract classes.(If you add an abstract method, the situation is the same as if you modify an interface.)

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.
If in a subsequent release, you add a new method, applications build against your interface will break unless the applications are updated.

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 a car put on its turn signal, or someone waves the flag at a parade, or a person swears "I do" at a wedding ceremony? Nothing is guaranteed. There is only a signal of intention, a speech act that other entities can recognize.)

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 (fields) but objects (with their members and hierarchy) 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 we can 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 that I call "cumulative obligation". 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 from some third party, 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. Here we also see that a subinterface can extend a comma-separated list of superinterfaces. Similarly, the implementing class can implement a comma-separate list of interfaces.

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?
http://download.oracle.com/javase/6/docs/api/java/util/Iterator.html
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. For example, the Internal Revenue Service will accept revenue from all items that implements the ITaxable interface, such as an electro-plated brass-alloy cross-saddle-split-clamp-reverse-threaded-opposite-spiraled-decoupling device disassembler, even if the IRS does not know what the taxable item is (or whether it is supercalifragilisticexpialidous or antidisestablishmentarian).

Array element of interface type

An array element can store an object of any type that implements the interface type. For example, the array of type ITaxable defined on line 22 accepts an object of type MonacoTax on line 23 because objects of this type can also be considered objects of type ITaxable.

Another example of this concept:

The output is:

Inventory@addbf1
Inventory@42e816
Inventory@9304b1

Method arg as interface type

Just as we refer to both a dermatologist and a brain surgeon as "doctor", so 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? Imagine we have a class with main called SeriesDemo.


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

A package is a set of related classes that can be grouped within the namespace specified by the name of the package.

Recall that packages organize the Java application programming interface:

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 by using the short name instead of the fully-qualified name.


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 with the syntax package packagename;

This declaration applies to all the classes in that file, making them all members of the declared package.

The demo class imports the package ujsing the syntax import packagename.*; where * is the wildcard for all the classes and interfaces of the package.

Download 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 came 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 strategy would have been to ask John, who more than the others encapsulated and controlled what the Beatles were about.

(In practice, the interface to the band members was through a phone call to their manager, Brian Epstein.)

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 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 default package has no name and is global to the directory that contains the classes.
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:

A common use case for protected is that you want to allow your customers, other developers, to subclass your class and put there subclass in their own package. You cannot know the name of the package that your customers will use, only that they will want to subclass your class.

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 Java archive (JAR) file contains the files of a package:  my-package-jar.jar
To run the jar, navigate to the directory that contains the jar file and issue this command at the console prompt: 
java -jar my-package-jar.jar

To see the contents, the command is:
jar tf my-package-jar.jar

and the result is:

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 directory named packages.
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 the directory directly 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.

So, the easiest way for Java to find the classes in a package is to look within the current directory for a subdirectory with the package name.

Another way is through the setting the operating system CLASSPATH environment variable, which can be set to include the path to a package. A final way is, at runtime, to include the -classpath option to specify the path to a package. These advanced techniques are discussed in Oracle's Java tutorial:  http://download.oracle.com/javase/tutorial/essential/environment/paths.html

Naming packages to avoid namespace collisions

By convention, a company should name its packages by using its internet URL in reverse as a prefix.
For example: com.mycompany.mypackage

Many software packages might have a print method, a save method, an authenticate method, and so on. Each package provides a namespace, which can be useful to avoid duplicate (colliding) names. Java's package naming convention is lowercase, using reverse URL order, so the ourStuff package should be renamed to our_stuff. Other examples of reverse-URL naming:

gov.irs.tax_breaks_for_the_rich

com.ibm.database

org.opensource.utilities.compiler

edu.berkeley.chemistry.biochemistry.next_generation_sequencing

http://java.sun.com/docs/books/tutorial/java/package/namingpkgs.html


Packing Java Itself

The 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 requires the package name

This is an example of a custom package. The general convention is that package name are all lowercase.

AccountBalance.class must reside in a directory named MyPack so that the Java interpreter can use the package statement to find the bytecode. Similarly, the BookPack directory must exist for the classes that belong to the BookPack package.

To compile: navigate one directory above the package directory and specify the relative path to the source code file, including the directory name that corresponds to the package name.

To run: navigate one directory above the package directory and specify the fully-qualified class name (including package name prefix with dot (.)

To prove that the package name is necessary:
1. Delete the two .class files.
2. cd into the BookPack directory.
3. Compile with java BookDemo.java
4. Try to run the bytecode with java BookDemo
5. Note that the Exception tells you the package name is required:

Let's look at an example of a package declaration in the source code.

What went wrong?

Two things.

(1) I need to change directories so that I am one level above the directory that contains the package.

(2) The command that invokes the interpreter to run the bytecode must include a reference to both the package 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. However, it is best to use the dot operator because protected subclasses might not be in the subdirectory.

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:\;


Controlling access and packages - review

A class can have only two levels of access:

A class member (constructor, 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
)
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 or protected for a class member but not for a package, which is either the implicit default or explicitly public.


Importing

To avoid having to specify the fully-qualified name of package, you can import it. Importing is a convenience to reduce typing.

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.

To compile and run:

D:\packages\test>javac AnimalPackageDemo.java

D:\packages\test>java AnimalPackageDemo

The output is:

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 lines because it must end with a blank line so that the utility knows it has read to the end of the file.
    For example,

    Line 1: Main-Class: PackageDemo
    Line 2:

    Except that Line 2 would not have characters, not even "Line 2".
     
  3. Make sure that there is exactly one (1) space between Main-Class: and the name of the class with main. If there are two or more spaces, the jar will NOT work!


     
  4. If you are writing on a Mac, also add a blank third line.
    Windows needs to see two characters (Line Feed, Carriage Return), but UNIX/Mac only use one character for a new line.
     
  5. 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 commercial jar zips up bytecode files, not source code files. Contrastingly, an OpenSource jar might contain source code but no compiled code, along with the manifest file.
     
  6. Create the executable jar at the command line, making sure to include the manifest, the .java, and the .class files.
    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 yourself and test.
  2. 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, a commercial customer  would not expand the .jar file (or even notice its existence). In some companies, the IT department might validate the jar before mass deployment. In any case, 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? (What is the statement and where must it be in the source code file?)

  2. What is the Java convention for package naming to ensure that Company-A's packages do not conflict with those of Company-B?

  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 by allowing you to avoid typing the fully-qualified name of each class that belongs to a package?

  4. Suppose that HeartSurgeon is a subclass of Surgeon, and that Surgeon defines a protected method named performSurgery()

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

  2. Which of the following does a class that implements an interface need to conform to:
    (a) the method names of the interface
    (b) the method signatures of the interface
    (c) the return types of the methods in the interface

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

  4. How many interfaces can a class implement?

  5. If ICanine is a subinterface that extends the IAnimal interface, can ICanine also extend ITaxable interface? Does the keyword extend enforce single inheritance?

  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? Similarly, can an array of type ITaxable store objects of any class type that implements the ITaxable interface?


Hash table - a data structure

Independent of Java or any specific programming language are the general data structures used in computer science to handle large amounts of data. Common data structures include arrays, stacks, queues, linked lists, trees, heaps, graphs, and hash tables.

A hash table is an associative array that provide one way to index a database, such as a dictionary with a spelling checker, that needs to quickly find any entry among a set of items of a stable size. Note: a compiler can create a dictionary of all the tokens in a program, and use a hash table to quickly access each item. (Other data structures are more appropriate if the data set frequently changes its size.)

A scenario:  it is not efficient to search and search with a single array containing 50,000 elements that represent each word in the English dictionary. We also do not want to create and maintain 50,000 arrays of one element each. Instead, we want the dictionary of 50,000 English words be stored and indexed in, say, 500 buckets. If we use only 26 buckets, such as the 26 letters of the alphabet, each bucket will have too many entries, and the bucket sizes will not be even because few words begin with "x" but many begin with "s".

A hash function generates a set of "buckets" to store the items in. It might start with the ASCII value of the letters in a word, then use the modulus operator to get a smaller range of numbers. A hash table algorithm might be:

arraySize = numberWords * 2; // * 2 provides extra space for collisions
arrayIndex = hugeNumber % arraySize; // smaller number of buckets

where hugeNumber represents the product of the ASCII value of every letter in the largest possible English word.

Suppose two words, "give" and "tick" happen to result in the same index value? We either put the extra word in the nearest empty bucket, or we implement each bucket as an array that can contain a reasonably small number of words.

This summary is based on Data Structures and Algorithms in Java by Mitchell Waite and Robert Lafore -   http://www.amazon.com/Structures-Algorithms-Mitchell-Waite-Signature/dp/1571690956. See also http://en.wikipedia.org/wiki/Hash_table.