Reputation: 6647
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
Reputation: 86774
Define an interface Colorable
with methods getColor
and setColor
and have colored shapes implement it.
Upvotes: 0
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