30.12.2013 Views

Chapter 6: Inheritance and Abstract Classes Chapter Topics 6.1 ...

Chapter 6: Inheritance and Abstract Classes Chapter Topics 6.1 ...

Chapter 6: Inheritance and Abstract Classes Chapter Topics 6.1 ...

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CS151 Object-Oriented Design<br />

Dr. Kim<br />

<strong>6.1</strong>.8 Notes<br />

Adding responsibilities: Decorator vs. <strong>Inheritance</strong><br />

Sometimes we want to add responsibilities to individual objects, not to an entire class. A<br />

graphical user interface toolkit, for example, should let you add properties like borders or<br />

behaviors like scrolling to any user interface component.<br />

• One way to add responsibilities is with inheritance. Inheriting a border from another class<br />

puts a border around every subclass instance. This is inflexible, however, because the choice<br />

of border is made statically. A client can't control how <strong>and</strong> when to decorate the component<br />

with a border.<br />

• Another way is to enclose the component in another object that adds the border. The<br />

enclosing object is called a decorator. The decorator conforms to the interface of the<br />

component it decorates so that its presence is transparent to the component's clients.<br />

Transparency lets you nest decorators recursively, thereby allowing an unlimited number of<br />

added responsibilities.<br />

Multiple <strong>Inheritance</strong><br />

In Java, a class can extend at most one immediate super class. Why ?<br />

• Multiple inheritance: the ability to extend more than one class<br />

• Multiple inheritance is a language feature that is difficult to implement <strong>and</strong> can lead to<br />

ambiguity. Therefore, Java does not allow a class to extend more than one class. Use<br />

multiple interfaces to emulate multiple inheritance.<br />

7

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!