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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With