|
Tech Tips Archive
November 6, 2001
WELCOME to the Java Developer Connection (JDC) Tech Tips,
November 6, 2001. This issue covers:
These tips were developed using Java 2 SDK, Standard Edition, v
1.3.
USING METHOD POINTERS
Suppose that you're using the Java programming language to
implement some type of a sort or search algorithm. Suppose too
that you need to pass to the algorithm a comparator method, that
is, a method used to compare and rank two elements.
A low-level language such as C supports function pointers,
which are memory addresses of functions. You can pass these
pointers to library functions such as qsort(), and combine qsort
and a comparator function you specify to perform arbitrary types
of sorting.
The Java programming language does not have pointers that are
visible to the user, and there are no global functions (methods).
Every method is a part of some class. So how can you designate
a particular comparator method for use when you're sorting,
searching, or doing similar kinds of operations? Here's one
approach:
class Compare {
public int compare(Integer a, Integer b) {
int aval = a.intValue();
int bval = b.intValue();
return aval < bval ? -1 :
(aval == bval ? 0 : 1);
}
}
public class MethPtr1 {
static int compare_ab(
Integer a, Integer b, Compare c) {
return c.compare(a, b);
}
public static void main(String args[]) {
Integer a = new Integer(47);
Integer b = new Integer(37);
int cmp = compare_ab(a, b, new Compare());
if (cmp < 0) {
System.out.println("a < b");
}
else if (cmp == 0) {
System.out.println("a == b");
}
else {
System.out.println("a > b");
}
}
}
|
In this example, the method compare_ab is a very simplified
version of a sort method. It's passed two Integer objects, along
with a comparator. The method then ranks the Integer objects,
returning -1 if the first object is less than the second, 0 if
they're equal, and 1 if the first object is greater than the
second.
The comparator is an instance of the Compare class that has a
method compare defined within it. The instance is called a
"function object," given that it defines a single method, and
that method performs operations on other objects that are passed
to the method.
An instance of Compare is created each time compare_ab is
called. This could be optimized by creating one instance of
Compare to be used throughout the program, or by using a
singleton class.
The output of the program is:
a > b
The approach above does the job, but it has some problems. One is
that there's a fixed ranking strategy built into the compare
method. If you wanted to reverse the order of comparison, or take
the absolute value of the numbers before comparing them, you'd be
out of luck. Also, a standard sorting or searching algorithm is
not going to know about a Compare class that you've defined; the
algorithm has to be implemented in terms of a standardized
mechanism.
To solve these problems, you can change the program like this:
import java.util.Comparator;
class Compare implements Comparator {
public int compare(Object a, Object b) {
int aval = ((Integer)a).intValue();
int bval = ((Integer)b).intValue();
return aval < bval ? -1 :
(aval == bval ? 0 : 1);
}
}
public class MethPtr2 {
static int compare_ab(
Integer a, Integer b, Comparator c) {
return c.compare(a, b);
}
public static void main(String args[]) {
Integer a = new Integer(47);
Integer b = new Integer(37);
Comparator c = new Compare();
int cmp = compare_ab(a, b, c);
/*
int cmp = compare_ab(
a, b, new Comparator() {
public int compare(
Object aa, Object bb) {
int aval = (
(Integer)aa).intValue();
int bval = (
(Integer)bb).intValue();
return aval < bval ? -1 :
(aval == bval ? 0 : 1);
}
});
*/
if (cmp < 0) {
System.out.println("a < b");
}
else if (cmp == 0) {
system.out.println("a == b");
}
else {
system.out.println("a > b");
}
}
}
|
java.util.Comparator is a standard interface that specifies the
compare method. This interface is used by other classes and
methods, for example, Collections.sort. You implement this
interface, defining whatever comparison method you desire.
Note that it's possible to use an anonymous inner class to
implement the Comparator interface. The example above shows an
alternative that illustrates the use of an inner class. This
approach is useful in situations where you only need to use the
implementing class in one place.
The example is a demonstration of programming using interface
types. When the MethPtr2 program calls compare_ab, the program
passes the method a Compare object. But the corresponding
parameter in compare_ab is defined as a Comparator. This is
roughly like saying:
Comparator x = new Compare();
This is valid because the Compare class implements the Comparator
interface. Another common example from the Collections Framework
is:
List x = new ArrayList();
Passing a method to another method, by means of a function object
or interface, so that the passed-in method can be called, is
sometimes referred to as a "callback." Here's a more explicit
example of a callback:
import java.util.*;
interface Visitor {
void visit(Object o);
}
class Walker {
public static void walk(Object o, Visitor v) {
if (o instanceof Map) {
o = ((Map)o).entrySet();
}
if (o instanceof Collection) {
Collection c = (Collection)o;
Iterator iter = c.iterator();
while (iter.hasNext()) {
v.visit(iter.next());
}
}
else {
throw new IllegalArgumentException();
}
}
}
public class MethPtr3 implements Visitor {
public void visit(Object o) {
System.out.println(o);
}
void doit() {
List data1 = new ArrayList();
data1.add("test11");
data1.add("test12");
data1.add("test13");
Walker.walk(data1, this);
Set data2 = new TreeSet();
data2.add("test21");
data2.add("test22");
data2.add("test23");
Walker.walk(data2, this);
Map data3 = new HashMap();
data3.put("test31key", "test31value");
data3.put("test32key", "test32value");
data3.put("test33key", "test33value");
Walker.walk(data3, this);
}
public static void main(String args[]) {
new MethPtr3().doit();
}
}
|
Suppose that you have a collection data structure, that is, a
List, Set, or Map, and you'd like to write a utility method
that
traverses the structure. As each element is visited, you'd also
like to call a method that you specify. The program above does
this.
Walker.walk is a static method that accepts a reference to a data
structure, along with an object of a class that implements the
Visitor interface. The method uses iterators to traverse the
structure, and it calls back to the visit method defined in the
MethPtr3 class. When you run this program, the result is:
test11
test12
test13
test21
test22
test23
test32key=test32value
test31key=test31value
test33key=test33value
|
Most of the time, using function objects and interfaces is the
right approach to implementing method pointers. But there's
another mechanism that's important to know. Suppose that you're
writing a debugger, interpreter, or similar type of program, and
you want it look up and call methods by their string name. In
other words, the user specifies a method name, and your program
calls this method. How would you do this?
This task is impossible in many other programming languages, but
Java's reflection features make it easy. Here's an example:
import java.lang.reflect.*;
class A {
public void f1() {
System.out.println("A.f1 called");
}
public void f2() {
System.out.println("A.f2 called");
}
}
class B {
public void f1() {
System.out.println("B.f1 called");
}
public void f2() {
System.out.println("B.f2 called");
}
}
public class MethPtr4 {
static void callMethod(Object obj, Method meth)
throws Exception {
meth.invoke(obj, null);
}
static void findMethod(String cname, String mname)
throws Exception {
Class cls = Class.forName(cname);
Method meth = cls.getMethod(mname,
new Class[]{});
callMethod(cls.newInstance(), meth);
}
public static void main(String args[])
throws Exception {
if (args.length != 2) {
System.err.println("missing class/method
names");
System.exit(1);
}
findMethod(args[0], args[1]);
}
}
|
After you compile this program, run it as follows:
java MethPtr4 A f2
Here you're specifying a class (A) and a method in the class to
be invoked (f2). The findMethod method loads a class
(Class.forName), and then finds a method within the class. Both
the class and method names are specified by strings. After the
method is found, it is represented by a Method object. The object
is passed to the callMethod method, along with an object of the
appropriate class.
This approach is powerful, but it's best not to use it unless you
really need it. For example, if you say:
java MethPtr4 A f3
you get an exception. By contrast, if you're not using
reflection, and you call a nonexistent method (f3) in your
program, you get a compile error. In other words, when you call
a method using reflection, some of the checking a compiler does
is necessarily deferred.
For more information about using method pointers, see
Section 11.2.6, The Method Class, in "The JavaTM Programming
Language Third Edition." by Arnold, Gosling, and Holmes. Also see
item 22, Replace function pointers with classes and interfaces,
in "Effective Java
Programming Language Guide" by Joshua Bloch.
ABSTRACT CLASSES VS. INTERFACES
In the JDC Tech Tips for October 9,
2001, there was
an item about using an abstract class hierarchy to implement the
Java equivalent of a C union. The code looked something like
this:
abstract class Time {
public abstract int getMinutes();
}
class Days extends Time {
private int days;
public int getMinutes() {
return days * 24 * 60;
}
}
class HoursMinutes extends Time {
private int hours;
private int minutes;
public int getMinutes() {
return hours * 60 + minutes;
}
}
|
A reader asked why an interface could not be used instead of an
abstract class, with the code written as follows:
interface Time {
int getMinutes();
}
class Days implements Time {
private final int days;
public Days(int days) {
this.days = days;
}
public int getMinutes() {
return days * 24 * 60;
}
}
class HoursMinutes implements Time {
private final int hours;
private final int minutes;
public HoursMinutes(int hours, int minutes) {
this.hours = hours;
this.minutes = minutes;
}
public int getMinutes() {
return hours * 60 + minutes;
}
}
public class AIDemo1 {
public static void main(String args[]) {
Time t1 = new Days(10);
Time t2 = new HoursMinutes(15, 59);
System.out.println(t1.getMinutes());
System.out.println(t2.getMinutes());
}
}
|
In fact, the interface approach does work. However, there are
a series of tradeoffs between the use of abstract classes and
interfaces. This tip examines some of those tradeoffs.
Both of these mechanisms define a contract, that is, required
behavior that another class must implement. If you have the
following definitions:
abstract class A {
abstract void f();
}
interface B {
void f();
}
|
then a concrete class that extends A must define f. A class that implements
B must define f.
Beyond this common feature, the two mechanisms are quite
different. Interfaces provide a form of multiple inheritance
("interface inheritance"), because you can implement multiple
interfaces. A class, by comparison, can only extend
("implementation inheritance") one other class. An abstract class
can have static methods, protected parts, and a partial
implementation. Interfaces are limited to public methods and
constants with no implementation allowed.
So what's the difference between using abstract classes and
interfaces in the example above? One difference is that an
abstract class is easier to evolve over time. Suppose that you
want to add a method:
public int getSeconds();
to the Time contract. If you use an abstract class, you can say:
public int getSeconds() {
return getMinutes() * 60;
}
In other words, you provide a partial implementation of the
abstract class. Doing it this way means that subclasses of the
abstract class do not need to provide their own implementation of
getSeconds unless they want to override the default version.
If Time is an interface, you can say:
interface Time {
int getMinutes();
int getSeconds();
}
But you're not allowed to implement getSeconds within the
interface. This means that all classes that implement Time are
now broken, unless they are fixed to define a getSeconds method.
So if you want to use an interface in this situation, you need to
be absolutely sure that you've got it right the first time. That
way you don't have to add to the interface at a later time,
thereby invalidating all the classes that use the interface.
Another issue with this example is that you might want to factor
out common data into the abstract class. There is no equivalent
to this functionality for interfaces. For example, if you say:
interface A {
int x = 7;
}
class B implements A {
void f() {
int i = x; // OK
x = 37; // error
}
}
|
all is well if you want to declare a constant in the interface,
but it's not possible to declare a mutable data field this way.
Let's look at another example:
import java.io.*;
interface Distance {
double getDistance(Object o);
}
interface Composite extends Comparable,
Distance, Serializable {}
class MyPoint implements Comparable, Distance,
Serializable {
//class MyPoint implements Composite {
private final int x;
private final int y;
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int compareTo(Object o) {
MyPoint obj = (MyPoint)o;
if (x != obj.x) {
return x < obj.x ? -1 : 1;
}
return y < obj.y ? -1 : (y == obj.y ? 0 : 1);
}
public double getdistance(object o) {
mypoint obj = (mypoint)o;
int sum = (x - obj.x) * (x - obj.x) +
(y - obj.y) * (y - obj.y);
return math.sqrt(sum);
}
}
public class aidemo2 {
public static void main(string args[]) {
mypoint mp1 = new mypoint(1, 1);
mypoint mp2 = new mypoint(2, 2);
double d = mp1.getdistance(mp2);
system.out.println(d);
int cmp = mp1.compareto(mp2);
if (cmp < 0) {
system.out.println("mp1 < mp2");
}
else if (cmp == 0) {
system.out.println("mp1 == mp2");
}
else {
system.out.println("mp1 > mp2");
}
}
}
|
MyPoint is a class that represents geometric X,Y points, with
the
usual constructor and accessor methods defined. The class
implements three interfaces. One interface is used to compare one
point to another, one is used to compute the Euclidean distance
between points, and the last declares that MyPoint objects are
serializable.
An alternate approach would be to define a new interface
Composite (called a "subinterface") that extends the three
interfaces, and then implement Composite in MyPoint. This is an
example of a "nonhierarchical type framework".
The output of the program is:
1.4142135623730951
mp1 < mp2
It's easy to retrofit an existing class to implement a new
interface. Doing this is sometimes called a "mixin." In a mixin,
a class declares that it provides some optional, side behavior in
addition to its primary function. Comparable is an example of
a mixin.
Note that it would be awkward to implement the AIDemo2 example
using abstract classes. Implementing several unrelated interfaces
in a class is hard to duplicate using abstract classes.
It's often desirable to combine interfaces and abstract classes.
For example, part of the design of the Collections Framework
looks roughly like this:
interface List {
int size();
boolean isEmpty();
}
abstract class AbstractList implements List {
public abstract int size();
public boolean isEmpty() {
return size() == 0;
}
}
class ArrayList extends AbstractList {
public int size() {
return 0; // placeholder
}
}
|
At the top of the hierarchy are interfaces, such as Collection
and List, that describe a contract, that is, a specification of
required behavior. At the next level are abstract classes, such
as AbstractList, that provide a partial implementation. Note that
size is not defined in AbstractList, but that isEmpty is defined
in terms of size. If a list has zero size, it is empty by
definition. A concrete class, such as ArrayList, then defines any
abstract methods not already defined.
If you use this scheme, and program in terms of interface types
(List instead of ArrayList), there are several benefits:
-
Much of the implementation work is already done for you in the
abstract classes.
-
You can easily switch from one implementation to another
(
LinkedList instead of ArrayList).
-
If
ArrayList or LinkedList are not satisfactory, you can
develop your own class that implements List.
-
If you cannot extend a given class, because you're already
extending another class, you can instead implement the
interface for the desired class and then forward method calls
to a private instance of the desired class.
Interfaces tend to be a better choice than abstract classes in
many cases, though you need to get the interface right the first
time. Changing the interface after the fact will break a lot of
code. Abstract classes are useful when you're providing a partial
implementation. In this case, you should also define an interface
as illustrated above, and implement the interface in the abstract
class.
For more information about abstract classes vs. interfaces, see
Section 4.4, Working with Interfaces, and Section 4.6, When to Use
Interfaces, in "The Java Programming Language Third
Edition"
by Arnold, Gosling, and Holmes.
Also see item 14, Favor composition over inheritance, and item 16,
Prefer interfaces to abstract classes, in "Effective Java
Programming Language Guide" by Joshua Bloch.
IMPORTANT: Please read our Terms of Use and Privacy policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
FEEDBACK
Comments? Send your feedback on the JDC Tech Tips to:
jdc-webmaster@sun.com
SUBSCRIBE/UNSUBSCRIBE
- To subscribe, go to the subscriptions
page, choose the newsletters you want to subscribe to and click "Update".
- To unsubscribe, go to the subscriptions
page, uncheck the appropriate checkbox, and click "Update".
- ARCHIVES
You'll find the JDC Tech Tips archives at:
http://java.sun.com/jdc/TechTips/index.html
- COPYRIGHT
Copyright 2001 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA.
This document is protected by copyright. For more information, see:
http://java.sun.com/jdc/copyright.html
This issue of the JDC Tech Tips is written by Glen McCluskey.
JDC Tech Tips
November 6, 2001
Sun, Sun Microsystems, Java, and Java Developer Connection are
trademarks or registered trademarks of Sun Microsystems, Inc. in
the United States and other countries.
|