Get the tools you need to learn Java skills fast!
Video tutorials, eBooks, hands-on lab exercises, sample code.
Get started
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

Win a copy of The Software Craftsman this week in the Agile forum!
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.

OCP Java SE 6 Programmer, OCM Java SE 6 Developer, OCE Java EE 6 JSPSD, OCE Java EE 6 EJBD, OCE Java EE 6 JPAD, Spring 3.0 Core Professional.
Frits Walraven
Creator of Enthuware JWS+ V6

Joined: Apr 07, 2010
Posts: 1929

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.
Have you tried LearnNowOnline?
subject: Wrappers & Subclasses