Compositions

What one mean by Compositions With Reference to MultipleInheritance.
[75 byte] By [airforce7a] at [2007-11-26 16:41:30]
# 1
> What one mean by Compositions With Reference to> MultipleInheritance.Composition and multiple inheritance have nothing to do with each other. Composition means that an object contains references to other objects. It should be used *instead* of inheritance where
CeciNEstPasUnProgrammeura at 2007-7-8 23:08:31 > top of Java-index,Java Essentials,Java Programming...
# 2

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);

}

duffymoa at 2007-7-8 23:08:31 > top of Java-index,Java Essentials,Java Programming...
# 3

> 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.

duffymoa at 2007-7-8 23:08:31 > top of Java-index,Java Essentials,Java Programming...