What is the Java equivalent of Cocoa delegates?
(I understand that I can have an interface passed to a class, and have that class call the appropriate methods, but I\'m
There's nothing stopping you from using the delegate pattern in your Java objects (It's just not a commonly used pattern in the JDK like it is in Cocoa). Just have a delegate
ivar of a type that conforms to your WhateverDelegate
interface, then in your instance methods that you want delegated, forward the method call onto the delegate object if it exists. You would probably end up with something that looks a lot like this, except in Java instead of Obj-C.
As far as optional interfaces go, that would be more difficult. I would suggest declaring the interface, declaring an abstract class that implements optional methods as empty methods, and then subclassing the abstract class, overriding the optional methods that you want this particular object to implement. There's a potentially severe limitation here due to the lack of multiple inheritance in Java, but that's as close as I could come up with.