Session 9 Lecture Notes for First Course in Java
course homepage      course calendar

12 May 2003

This lecture covers the reading in Chapter 9: Packages and Interfaces and Chapter 10: Exception Handling

Packages

Interfaces

Exception Handling


Quiz

Homework Assignment: Prepare for Final Exam

Packages

Sun's website on packages: http://java.sun.com/docs/books/tutorial/java/interpack/packages.html

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

Every class requires a public class declaration so that the class be accessed in some manner. Optionally, a class can work with one or more packages.

A package enables the convenient grouping of related classes, as well as the encapsulation of namespace and visibility.

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.

Throughout the course, we have seen examples involving the import of various packages whenever we needed functionality beyond that of the default package, java.lang

When we import a package, the namespace of its classes are immediately visible to the compiler.

Declaring

AccountBalance.class must reside in a directory named MyPack so that the Java interpreter can use the package statement to find the bytecode:

java MyPack.AccountBalance

The command line must reference the fully-qualified class name, that is, with the prefix for the package.
Alternatively, you can update the classpath environment variable to point to the directory for the package, which product installers often do.

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

Controlling access

Remember that the class is a feature of Java that supports encapsulation. Many methods and properties in a class can be hidden or private.
Similarly, a group of classes, that is, a package, can also have access protection. The visibility rules apply to all class members, but for example, let us suppose that I have a class, MyClass, in a package, MyPackage.

The default access control does not require a keyword and means that MyClass is visible to its subclasses as well as to other classes in the same package.

Example

Run the demo program from a directory above that in which the class files reside.

D:\java\teachjava\spring2003\session9\packages>java p1.Demo
The output is:

These result show:

Importing

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;

Interfaces

An interface is a sort of functional specification about WHAT a class does, not HOW it does it.
An interface supports polymorphism because it leaves to classes the implementation.

Whereas a class can only inherit from one superclass (even if the class hierarchy creates a vertical chain), a class can implement multiple interfaces.

Dynamic method resolution at runtime means that you do not need to design a class hierarchy in which all the functionality trickles down from superclasses. Interfaces provide an alternate route to functionality without breaking the principle of single inheritence.

Defining an interface

When you define an interface, you specify methods and/or variables but do not fill in method code blocks, that is, you do not implement.

interface MyInterface {
  void myMethodX(double myParameter);
  boolean myMethodY(); 

Implementing an interface

The interface cannot implement the classes it specifies, not even one of them.
The class that implements an interface must implement all the classes specified in the interface.

Abstract classes versus Interfaces

What if you only want to implement some of the classes in the interface?
In this case, the implementing class must be declared an abstract class with the modifier abstract.

abstract class MyPartialImplementationClass implements YourInterface {
// implementation code

Extending an interface

An interface can both extend the interface from which it inherits.

The output is:

Implement meth1(), from interface A.
Implement meth2(), also from interface A.
Implement meth3(), from interface B.

**************

http://java.sun.com/docs/books/tutorial/java/concepts/interface.html

What Is an Interface?

In English, an interface is a device or a system that unrelated entities use to interact. According to this definition, a remote control is an interface between you and a television set, the English language is an interface between two people, and the protocol of behavior enforced in the military is the interface between people of different ranks. Within the Java programming language, an interface(in the glossary) is a device that unrelated objects use to interact with each other. An interface is probably most analogous to a protocol (an agreed on behavior). In fact, other object-oriented languages have the functionality of interfaces, but they call their interfaces protocols.

The bicycle class and its class hierarchy defines what a bicycle can and cannot do in terms of its "bicycleness." But bicycles interact with the world on other terms. For example, a bicycle in a store could be managed by an inventory program. An inventory program doesn't care what class of items it manages as long as each item provides certain information, such as price and tracking number. Instead of forcing class relationships on otherwise unrelated items, the inventory program sets up a protocol of communication. This protocol comes in the form of a set of constant and method definitions contained within an interface. The inventory interface would define, but not implement, methods that set and get the retail price, assign a tracking number, and so on.

To work in the inventory program, the bicycle class must agree to this protocol by implementing the interface. When a class implements an interface, the class agrees to implement all the methods defined in the interface. Thus, the bicycle class would provide the implementations for the methods that set and get retail price, assign a tracking number, and so on.

You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following:

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.


Exception Handling

Sun's tutorial: http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

In Java terminology, an error is something beyond the programmer's control.
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Error.html

In Java's object-oriented language, an error is an object.
Also, an exception is an object.
The default java.lang package defines the Exception class:
http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Exception.html

Both Error and Exeption inherit from Throwable (that is, they can occur at runtime), and Throwable inherits from Object.
Throwable provides methods that are common to errors and exceptions (re-use code!), such as getCause() and toString().
So you see that exception handling is fundamental to the architecture of the Java language.

As a programmer, you can do prepare for the possibility of an exception by writing coded to handle the exception.

Unchecked exceptions

However, some exceptions are so foreseeable that Java automatically handles them. These are exceptions that the compiler does not check for in YOUR code, and so are these exceptions are called "unchecked exeptions":

The following example is for an unchecked exception: divide by zero.

The output is:

Division by zero causes this error:
java.lang.ArithmeticException: / by zero
After catch statement.

Note that e.toString() is possible because every exception object inherits from the class Throwable.

Catching more than one exception

In the following except, one catch clause deals with

With no command-line arguments, the output is:

a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.

With command-line arguments, the output shows a different exception:

D:\java\teachjava\spring2003\session9>java MultiCatch 22 34 hello
a = 3
Array index oob: java.lang.ArrayIndexOutOfBoundsException: 42
After try/catch blocks.

Declaring that a method throws exceptions

The keyword throws indicates that a method can throw an exception that it does not handle. This declaration does permit another method to handle the exception.

In this case, the unhandled exception in line 4 is propagated up to the main method, the caller.
You can have a superclass handle a group of exceptions that get thrown up to the superclass from a group of subclasses.
Or, you might choose to handle the exception locally.

Cleaning up with finally

Checked exceptions

The compiler does check to see if you handle the following kinds of exceptions if the compiler expects your code is likely to cause these exceptions:

Defining your own exceptions

Because Exception is an exposed class, you can subclass it (polymorphism) for your needs.

The output is:

Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]

Quiz

  1. What does the keyword package mean?
  2. Why is it useful to use packages?
  3. What are the modifiers for package access and what do they mean?
  4. What is the difference between an abstract class and an interface?
  5. What are the keywords associated with an interface and what do they mean?
  6. What makes execution skip over the catch block?
  7. What makes execute skip over part of the try block?
  8. What is the difference between an exception and an error?
  9. When do you use throw?
  10. When do you use throws?
  11. What does the code block following finally do if there is an exception?
  12. What does the code block following finally  do if there is no exception?

Homework Assignment

Prepare for the final by reviewing what we have learned during the course.

Review the entire course in preparation for the final exam.

______________
course homepage      course calendar