What you want are Interfaces.
Each interface can mandate a characteristic. A class can implement multiple interfaces as it pleases:
interface Foo {
boolean doFoo();
}
interface Bar {
boolean doBar();
}
class fooImpl implements Foo {
boolean doFoo(){
. . .
}
}
class barImpl implements Bar {
boolean doBar(){
. . .
}
}
class fooBarImpl implements Foo, Bar {
boolean doFoo(){
. . .
}
boolean doBar(){
. . .
}
}
UPDATE
Alternatively, implement the state pattern. One state would be HasABar, and would provide the desired behavior for when your Foo has a Bar. Another state might be HasABat, providing different behavior. Your Foo object may start with HasNothing, until you give it a Bar, which would change the state to HasABar.
interface FooState {
Drink getDrink() throws InvalidStateException;
}
class HasNothing implements FooState {
Foo foo;
HasNothing(Foo foo) {
this.foo = foo;
}
Drink getDrink() throws InvalidStateException {
throw new InvalidStateException("There's no Bar");
}
}
class HasABar implements FooState {
Foo foo;
HasABar(Foo foo) {
this.foo = foo;
}
Drink getDrink() throws InvalidStateException{
Foo foo.getBar().getDrink();
}
}
class Foo {
FooState state;
Bar bar;
public Foo() {
state = new HasNothing(this);
}
Bar getBar() {
return bar;
}
void setBar(Bar bar) {
this.Bar = bar;
if (null != bar) {
state = new HasABar(this);
}
else {
state = new HasNothing(this);
}
}
Drink getDrink() throws InvalidStateException{
return state.getDrink();
}
}
At this point you are not really dealing with subtypes, you've got one type that behaves differently depending on state during runtime.