|
|
We mentioned that the Java(TM) programming language is syntactically powerful. As an example of this expressiveness, as well as expression evaluation order, this panel demonstrates how to design a class that supports "chained method evaluation." Java virtual machines evaluate expressions from left to right, subject to the standard operator precedence rules. Of course, evaluation order can be controlled with groups of parentheses, as with other languages:
int x = (4 + 32) / (2 + 1); // x == 12
We mentioned that the new operator has a convenient left-to-right evaluation precedence that facilitates one-shot creation of objects, followed by a method invocation to perform some operation:
new Dog().bark();
The expression evaluation proceeds as follows:
An important point is that the Java programming language continues this "evaluation plus binding" strategy in a left-to-right fashion until it consumes the entire expression. Thus, as long as "something" to the left of a dot evaluates to an object and "something" to the right of a dot evaluates to a method, the Java virtual machine will bind the method to the object and perform the operation. Consider the following program:
public class EvalDemo {
public static void main(String[] args) {
EvalDemo e = new EvalDemo();
e.printIt("One, ")
.printIt("Two, ")
.printIt("Three.");
}
public EvalDemo printIt(String s) {
System.out.print(s);
return this;
}
}
It defines the method printIt(), which has an interesting design. The return type is the class name, EvalDemo, and the method finishes with a return statement for the current instance itself, namely, this. Thus, given an instance of this class, we can write code such as the following:
e.printIt("One, ").printIt("Two, ").printIt("Three.");
Each invocation of printIt() performs a unit of work, in this case, displaying a message, and then again yields (evaluates to) the current object. The expression evaluation then continues with
<current-object>.printIt("Two, ").printIt("Three.");
and so on, until the entire expression is consumed.The output from this program confirms the left-to-right evaluation:
D:\>java EvalDemo
One, Two, Three.
Anytime you have a class design with void methods, that is, the methods otherwise do not need to return a particular value, you can use this strategy to support method chaining. copyright 1996-2000 Magelang Institute dba jGuru |
|