Concepts of Programming Languages

(Sean Pound) #1
12.7 Support for Object-Oriented Programming in Java 555

implementation of a method to compare the elements to be sorted. The
generic Comparable interface provides the protocol for this comparing
method, which is named compareTo. The code for the Comparable inter-
face is as follows:

public interface Comparable <T> {
public int compareTo(T b);
}

The compareTo method must return a negative integer if the object
through which it is called belongs before the parameter object, zero if they are
equal, and a positive integer if the parameter belongs before the object through
which compareTo was called. A class that implements the Comparable inter-
face can sort the contents of any array of objects of the generic type, as long as
the implemented compareTo method for the generic type is implemented and
provides the appropriate value.
In addition to interfaces, Java also supports abstract classes, similar to
those of C++. The abstract methods of a Java abstract class are represented as
just the method’s header, which includes the abstract reserved word. The
abstract class is also marked abstract. Of course, abstract classes cannot be
instantiated.
Chapter 14 illustrates the use of interfaces in Java event handling.

12.7.3 Dynamic Binding


In C++, a method must be defined as virtual to allow dynamic binding. In Java,
all method calls are dynamically bound unless the called method has been
defined as final, in which case it cannot be overridden and all bindings are
static. Static binding is also used if the method is static or private, both of
which disallow overriding.

12.7.4 Nested Classes


Java has several varieties of nested classes, all of which have the advantage of
being hidden from all classes in their package, except for the nesting class. Non-
static classes that are nested directly in another class are called inner classes.
Each instance of an inner class must have an implicit pointer to the instance
of its nesting class to which it belongs. This gives the methods of the nested
class access to all of the members of the nesting class, including the private
members. Static nested classes do not have this pointer, so they cannot access
members of the nesting class. Therefore, static nested classes in Java are like
the nested classes of C++.
Though it seems odd in a static-scoped language, the members of the
inner class, even the private members, are accessible in the outer class. Such
references must include the variable that references the inner class object. For
Free download pdf