File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes Wrappers & Subclasses Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "Wrappers & Subclasses" Watch "Wrappers & Subclasses" New topic

Wrappers & Subclasses

Nidhi Sar
Ranch Hand

Joined: Oct 19, 2009
Posts: 252

Feeling a little confused about wrappers - about what their purpose is.

Quoting from HFSJ:

"The Decorator/Wrapper decorates/wraps one kind of an object with an "enhanced" implementation. And by "enhanced", we mean "adds new capabilities" while still doing everything the original wrapped thing did."

Ok, so isn't that exactly what extending the class is - when you extend a class, the new class does everthing the original class did and adds new capabilities. So how is a wrapper object different from a subclass object?

"A problem well stated is a problem half solved.” - Charles F. Kettering
Piotr Nowicki
Ranch Hand

Joined: Jul 13, 2010
Posts: 610

The main difference is about WHEN you add these new capabilities.

Using inheritance, you do it during compilation time (A extends B).
Using the decorator pattern, you do it during runtime (new BufferedReader(...)).

The wrapping/decorating is therefore more flexible, as you can change (add) the behavior dynamically.

Edit: oh, and remember about situations when you just can't extend some class and you still wish to add some new features to it.
Frits Walraven
Creator of Enthuware JWS+ V6
Saloon Keeper

Joined: Apr 07, 2010
Posts: 2099

Hi Nidhi,

Everything that Pedro says is true.

and the obvious difference with inheritence is:
DecoratorOfA has a A

The decorator class has an instance variable of A, and maybe other instance variables and methods to add new features to A.

Nidhi Sar
Ranch Hand

Joined: Oct 19, 2009
Posts: 252

Thanks guys, that makes it much clearer.
I agree. Here's the link:
subject: Wrappers & Subclasses
It's not a secret anymore!