When to use a Composite and when a Component

Here’s an example:

If you want to create a reusable custom component class
NumberField
for inputting only integer values, you could just simply extend
TextField
, and in the constructor call:

setPattern(“[0-9]
*”);
setPreventInvalidInput(true);

The problem with this is that now the
NumberField
has all the same public methods that
TextField
has. So the user of the component can for example call
setPattern()
again and allow inputting something else than numbers into it. You don’t want
NumberField
to have that method.

To avoid this, you can hide the
TextField
API by wrapping it inside a
Composite
:

public class NumberField extends Composite {
public NumberField() {
getContent().setPattern(“[0-9]
*”);
getContent().setPreventInvalidInput(true);
}
}

Now you can decide what API to expose to the user. The
TextField
has
setValue()
and
getValue()
methods for type String but those aren’t inherited anymore and you could implement those methods for the int-type to make the
NumberField
serve it’s purpose better and do the String-int conversions for the user.

I hope this helps :slight_smile: