Session 8 Lecture Notes for First Course in Java

(syllabus and calendar)

 

Interfaces - more abstract than abstract classes


Reflection


Jar instructions


Packages

Exception Handling


Quiz and Homework Assignment

Help for Homework

Zip-Spring2007

Zip - August 2006

zip of quiz answers and in-class examples Nov 05

zip of examples         zip with Aug 1, 2005 comments

Interfaces - more abstract than abstract classes

Last week, we worked with abstract classes. An abstract class has one or more abstract methods.
An abstract method is a template for making (implementing) a method. It specifies the parameter signature and the return type. Nothing more.

An abstract class permits partially 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 permits--at its level--no implementation, not even partial implementation.

Let's summarize:

Interfaces, for purposes of design, avoid the constraint of single inheritence. 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. For First Course in Java, we will 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 but ISeries is NOT a class.
Note the keyword implements, which signals the compiler that this class follows the specifications of the ISeries interface.


 


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.

If we want to be theoretical, we could say that 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.

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.

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 specifying functionality without breaking the principle of single inheritance.

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.

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

Most often, one finds methods in an interface. An interface specifies class members independent from, and prior to, any implementation or instantiation. 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.

Here is the syntax for creating a static variable inside an interface.

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: there is no such thing as an object of type interface, or an object of type abstract class.

Extending an interface

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.
This is not common, but that it is possible shows that architects of Java generally strive to make the language systematic and logical.

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

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. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.


Reflection

Last week, we saw an empty interface for serialization. Serialization means to take apart an object, move it over the network, then put it back again. Serialization relies of reflection, as does the inheritance shown in the javadoc for the Java's API.

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]


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 must end with a blank line.
    For example,

    Line 1: Main-Class: DemoJar
    Line 2:

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

    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.
     
  3. Create the executable jar at the command line.
    For example,
    jar cmf myManifestFile.txt myJarFile.jar *.*
    where jar invokes the jar utility, cmf means create a jar with the manifest file, myManifestFile.txt is the file discussed in Step 2, myJarFile.jar is the name of the jar (which normally ends in .jar to indicate that it is a jar file), and *.* means to include all the files in the current directory in the newly created jar.
    Note that many software vendors ship their jar with the .class files but not the .java files. However, your instructor does want to see your source code.
     
  4. 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.

Note: This following attachment is a zip file that contains a jar. To extract the zip, use the password blankline
   
jar.zip


Packages

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

Another example:

javac BookPack/BookDemo.java

java BookPack.BookDemo

The following example runs a program that imports three packages:

D:\__09Fall\lecture8examples\lecture\packages>javac RunStuff.java

D:\__09Fall\lecture8examples\lecture\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

Remember that the class is the feature of Java that supports encapsulation. Many methods and properties in a class can be hidden or private. 

For example, let us suppose that I have a class, MyClass, in a package, MyPackage.

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

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

 

 

 

 

D:\_sessions06summer\8\lecture\packages\test>java AnimalPackageDemo
Inside AnimalPackageDemo
Beast roar
Dogs might fetch


Exception Handling

An Exception is an event that is not normally wanted during the execution of a program.. Unless we handle errors, the first one halts execution.

If we handle errors Java's built-in try/catch mechanism, errors can occur without blocking program execution.

You can create your own custom exception type.


Exception handling is built into the architecture of the Java language and is an example of how the object-oriented paradigm is fundamental to the language.

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

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Throwable.html
   java.lang.Throwable is the superclass for both Error and Exception
In Java terminology, an Error is something beyond the programmer's control and something the programmer should not try to handle.
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Error.html
An Exception is a potential problem that your application should consider.
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Exception.html


The default java.lang package defines both the Exception class and the Error class. When an actual problem occurs, the virtual machine can construct an object of type Exception . This object inherits methods from its superclass, Throwable, that are useful for diagnosis the problem.
 

Both Error and Exception 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().
 

As a programmer, you 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. The compiler handles these exceptions, the compiler does not check to see if you handles them in YOUR code, and so you can leave these so-called "unchecked exeptions" unchecked:

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

The mechanism to handle Exception objects involves two keywords: try and catch. The block encloses what we suspect might throw an Exception object. The catch block handles the Exception object.

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

Catching more than one exception

In the following except, each catch clause is defined to handle a different type of runtime Exception object.

The output above is with no command-line arguments, which causes a divide-by-zero exception on line 7..

With 3 command-line arguments, the output shows a different exception because line 11 tries to access the 43rd element in an array that only has 3 elements:

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.

Call Stack Location of Exception Handling

In this case, the unhandled exception in line 5 is propagated up the call stack to the caller, which in this case is the main method.
An unhandled exception is always propagated up the call stack until it is handled or reaches its caller.
You can have a superclass handle a group of exceptions that get thrown up to the superclass from a group of subclasses.
The advantage of using a superclass to handle exceptions is that you can centralize the logic and maintenance, which can ensure consistency, improve debugging, and facilitate maintenace.
Or, you can handle the exception locally.
An advantage of local handling is that it is more simple. If the coding is work is being done by different programmers, it might be quicker to let each programmer handle her or his own Exceptions.

Here is another example that "throws" an exception (a custom exception), and it has a "finally" block (described in the following section): CallStackExampleWithCustomException3.java

Cleaning up with finally

You might want a method to do some cleanup, such as close a database connection, whether or not an exception occurs.

Checked exceptions

The compiler checks 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 (customize it) for your needs. Java provides specific Exceptions for the core APIs, but only domain programmers know what domain objects and Exceptions they need.


Exception Handling continued

To review, all Exceptions are a subclass of Throwable: http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Throwable.html

This allows for code re-use and default behavior. If Throwablewere an interface, Exceptions would not inherit default behavior, such as GetStackTrace
   http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Throwable.html#getStackTrace()
and toString
  http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Throwable.html#toString()

In  Java, objects of type Error are beyond the programmer's control, and Error objects also inherit the default behavior of Throwable.

Some Exceptions are built into Java's API specification. For example, the ArithmeticException occurs if a program tries to divide a number by zero.
   http://java.sun.com/j2se/1.4.1/docs/api/java/lang/ArithmeticException.html

You can have a catch statement for each type of exception.

To ensure that a specialized exception is handled, make its catch block precede the catch block of its superclass. Otherwise, the more general superclass will handle the subclass exceptions, and you lose the ability to ever get to the specialized exception.

The compiler complains:

ExcDemo5.java:20: exception java.lang.ArrayIndexOutOfBoundsException has already been caught
catch (ArrayIndexOutOfBoundsException exc)

You can have inner try blocks for specialized errors, and reserve the outmost try block for the error handling to use if all the previous attempts fail.

To create your custom exception class, you extend Java's Exception class. As always, you need to create an exception object, and your catch block must provide a reference to the exception object.

Another example:

The following program reads from a file by using the read method of the Java io package. The first line of the program is the import statement that gives this application access to all the members of the io package. Which two exceptions does the following program handle?

If I give a file name as a command-line argument, the program prints to the screen the contents of the file:


Quiz

  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, say, three uniquely named classes that belong to, say, three different packages, what would make writing your code more convenient?
  4. Suppose that that the subclass whose members you want to call belongs to a different package. Is that a problem if the class is declared:
  1. public?
  2. protected?
  3. no access modifier specified?
  1. What is the difference between an abstract class and an interface in terms of
    1. writing the actual code for specific functionality?
    2. inheritance?
  2. What are the keywords associated with an interface and what do they mean?
  3. What makes execution skip over the catch block?
  4. What makes execute skip over part of the try block?
  5. What is the difference between an exception and an error?
  6. When do you use the keyword throw?
  7. When do you use the keyword throws?
  8. What does the code block following finally do if there is an exception?
  9. What does the code block following finally  do if there is no exception?
  10. Last week we saw how inheritance is enforced by a subclass implicitly calling the constructor of its superclass. Should we write our code so that superclass version of the exception is called first?