views:

80

answers:

2

Hi, the above explanation is very nice.

However, I am slightly confused by the implementation of Decorator Pattern (DeP) as given in

http://www.netobjectives.com/resources/books/design-patterns-explained/java-code-examples/chapter17/#17-1

The design for above linked code is given at tinypic.com/view.php?pic=xnaqlt&s=3

I am confused by "super.callTrailer();" in the decorator classes Header1, Header2, Footer1 and Footer2, all derived from TicketDecorator.

Shouldn't it be just "callTrailer();" ? As each decorator object would have its own reference to the next decorator due to the line "private Component myTrailer;".

Note: I am not very well versed in Java and a beginner in Design Patterns.

+2  A: 

They will both give you the same result. Since callTrailer() only exists in the parent class then calling callTrailer() by itself will automatically call the callTrailer() of the TicketDecorator. I guess the reason they put super in there is to make it explicit that it is calling the parent's method.

Romain Hippeau
Thanks.But.. If a class B is derived from A. And A has a method x(). B doesn't define (override) x(). So now B also a method x() that can access any members of B. Right? I mean x() is an instance method of B.
Imran
@Imran - if there is no override then If you call x() on B it will call the one on A.
Romain Hippeau
ok. lets say x() modifies a private member "pv". And as u say x() called is the one in A. Which "pv" is modified? The "pv" in A or the "pv" in B?
Imran
You cannot have a pv in B with the same name. It would modify the one in A.
Romain Hippeau
And if A is an abstract class, and it has a method y(), that B overrides to have a call super.x(). Now B's "pv" is the only one that x() shall be able to "see"?
Imran
@Imran Lookup the Liskov Substitution principle( http://en.wikipedia.org/wiki/Liskov_substitution_principle ). The idea is to have an is-a relationship All the methods in the abstract class should be self contained and apply to any sub-classes. You cannot have a method in a super class that modifies instance variables in a child class.
Romain Hippeau
A: 

@Romain: Thank you for your patience. I think I am beginning to understand that the code of x() will be taken from the class A (where it is defined). But it will execute as if invoked on an object of B i.e. it will execute in the context(state/members) of an object of derived class B.

Imran