DrYap
DrYap

Reputation: 6647

Extend concrete base class of hierarchy

Say I was using a library for shapes which offered:

class Shape
class Circle extends Shape
class Square extends Shape

but I want introduce the concept of red shapes. I cannot modify the library but I can create:

class RedShape extends Shape

however this cannot be easily extended to RedCircle as it cannot extend both RedShape and Circle.

I don't think the decorator pattern quite works here but is there a technique for achieving this?

Upvotes: 5

Views: 68

Answers (2)

Jim Garrison
Jim Garrison

Reputation: 86774

Define an interface Colorable with methods getColor and setColor and have colored shapes implement it.

Upvotes: 0

jan.supol
jan.supol

Reputation: 2805

Short answer can be found in Effective java by Josh Bloch, Item 16: Favor composition over inheritance.


EDIT: Composition is what you would need to do, really. Multiple inheritance is not allowed with java. People have tried. They have some approaches. They are writing papers about it. They even use code generating tools, or proxy (not jdk proxy in your case, it cannot make proxy of a class), but nothing is as elegant as you would probably like.

Upvotes: 1

Related Questions