On Jan 28, 4:15 pm, Farcus Pottysquirt <where_is_my_...@movies.net>
wrote:
> Sorry for the lengthiness of this post, but in order to illustrate my
> question, I needed to include all the relevant classes.
[quoted text clipped - 26 lines]
> flyBehavior = new FlyWithWings();
> flyBehavior = new FlyNoWay();
snipped...
> Why would it not show the results from both flyBehavior references like such
>
[quoted text clipped - 6 lines]
> I can't fly
> BUILD SUCCESSFUL (total time: 1 second)
Because there is only one 'flyBehaviour' reference and it was over
written to point to an instance of the 'FlyNoWings' class.
To get both behaviours, you would could over ride the
Duck.performFly() method to call fly() on two 'flyBehaviour classes.
e.g.
public class MallardDuck extends Duck {
private FlyBehaviour flyBehaviour1;
private FlyBehaviour flyBehaviour2;
/** Creates a new instance of MallardDuck */
public MallardDuck() {
quackBehavior = new Quack();
flyBehavior1 = new FlyWithWings();
flyBehavior2 = new FlyNoWay();
}
public void performFly() {
flyBehavior1.fly();
flybehaviour2.fly();
}
public void display() {
System.out.println("I'm a real mallard duck");
}
}
Alternatively, you could use the Decorator Design Pattern (page 88 of
your book).....
Farcus Pottysqirt - 29 Jan 2007 00:07 GMT
> Because there is only one 'flyBehaviour' reference and it was over
> written to point to an instance of the 'FlyNoWings' class.
So based on this, would you say that the following evaluation of the
"process" is correct?
<interpretation>
An object of type Duck is instantiated as a new Mallard Duck
A mallard duck inherits its:
flyBehavior : reference variable
quackBehavior : reference variable
performFly : method
performQuack : method
from the abstract class Duck
It has it's own swim method
A mallard duck overrides the display method
The MallardDuck constructor sets
quackBehavior = Quack
flyBehavior = FlyWithWings
When the new mallard is created, the call to performQuack calls Quack
the call to performFly calls flyWithWings
The quackBehavior interface has one empty method called quack which must
be implemented by every class that implements the interface.
</interpretation>
> To get both behaviours, you would could over ride the
> Duck.performFly() method to call fly() on two 'flyBehaviour classes.
>
> Alternatively, you could use the Decorator Design Pattern (page 88 of
> your book).....
I haven't gotten that far yet, but I'm working on it :-)