When a superclass defines a field or non-private method, it is inherited by all
when a superclass defines a field, the field exists in all subclass objects
when a superclass defines a non-private method, it may be called on an instance
An exception in Java is an unexpected event which makes further progress within a
For example, we saw last time that when we try to open a file using
a FileInputStream or FileReader, but the file we're trying to open doesn't
Java defines a number of standard interfaces that you can have your own classes
implement. One such interface is java.lang.Comparable. The Comparable interface
looks something like this:
public interface Comparable cfw_
public int compareTo(Obj
The BufferedReader class is handy for reading a text file line-by-line.
Here is a program to find the longest line in an input text file:
To be able to implement generic methods and containers, we need the abililty to
define generic types in the program. A generic type is one that could point to objects
of many different classes.
There are two approaches to generic types in Java: java.lang.
As a simple example program, we will implement a GUI application which displays
an integer count. Each time the mouse is clicked, the count increases. Mouse clicks
also cause a rectangle displayed in the window to change color.
The comments in the example
Instanceof, Type casts
Sometimes it is useful to find out whether a superclass reference points to an instance
of a particular subclass. We can do so using the instanceof operator. For example:
public void startTrip(Vehicle v) cfw_
if (v instanceof Airpla
Recall that we noted that something was wrong with our readFirstLine method.
What's wrong with the method is somewhat subtle:
If the file is opened successfully, and
an IOException occurs trying to read a line from the file, then
public enum Terrain cfw_
public abstract class Vehicle cfw_
public abstract boolean startTrip(Terrain t);
public abstract boolean endTrip(Terrain t);
public abstract boolean move(Terrain t);
Inheritance is an IS-A relationship between two classes.
For example, consider the classes Vehicle, Car, Boat, and Airplane.
A Car is a Vehicle.
A Boat is a Vehicle.
An Airplane is a Vehicle.
We describe IS-A relationships using a class hierarchy diagram: