Here's a simple example of using an interface, composition, and mixin behavior to change a class dynamically at runtime. - %
package cruft;
import javax.swing.JOptionPane;
public class CompositionExample implements Mixin
{
private Mixin composition;
private static final String DEFAULT_MESSAGE = "All mixed up";
public static void main(String[] args)
{
CompositionExample example = new CompositionExample();
String message = ((args.length > 0) ? args[0] : DEFAULT_MESSAGE);
example.setComposition(
new Mixin()
{
public void doIt(String message)
{
System.out.println(message);
}
}
);
example.doIt(message);
example.setComposition(
new Mixin()
{
public void doIt(String message)
{
JOptionPane.showConfirmDialog(null, message, message, JOptionPane.OK_OPTION);
}
}
);
example.doIt(message);
}
public void setComposition(Mixin composition)
{
this.composition = composition;
}
public void doIt(String message)
{
composition.doIt(message);
}
}
interface Mixin
{
void doIt(String message);
}
> What one mean by Compositions With Reference to
> MultipleInheritance.
There are two major ways to reuse implementation in OO and that's object composition and class inheritance.
There's also a rule of thumb stating that you should prefer object composition over class inheritance. This means that a class should get its hands on implementation by holding objects rather than by inheriting classes.
In Java the above rule is slightly off because there is no multiple class inheritance available so a class is very much forced to use object composition once it has inherited the single class it's allowed to inherit.