The aliasing used when calling methods isn??™t available when implementing them. That??™s why you have to
write fatalError, and not fatal_error.
?– Caution If the method you??™re implementing should return a Java value, make sure the value you return
from the method can be coerced into Java without problems.
You can also implement more than one interface, in mostly the same way:
class RunCompare
import java java.lang.Runnable
import java.lang.Comparable
def compareTo o
this <=> o
end
def run
puts "running..."
end
end
java.lang.Thread.new(RunCompare.new)
java.util.TreeSet.new(RunCompare.new)
Notice that you can only do this the first time you open up a class. Because Java integration
needs to generate a proxy class beneath the covers, this can only be done once. As you
can see from the example, you can send instances of this class into everything that can take
either a Runnable or a Comparable. One thing to note about implementing interfaces is that up
until now you??™ve had to create a new class explicitly. This can pollute the namespace, and isn??™t
always necessary. Many times you just want something like an anonymous implementation of
the interface. You can also have that with the impl method:
button.set_action_listener java.awt.event.ActionListener.impl { |_,e|
e.source.text = "Hello World"
}
CHAPTER 6 ?– JAVA INTEGRATION 106
impl is a method that exists on all interfaces. It takes a block in some form that should be
executed when any of the methods in the interface is called.
Pages:
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192