Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend concrete base class of hierarchy

Tags:

java

oop

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?

like image 604
DrYap Avatar asked Nov 08 '22 12:11

DrYap


1 Answers

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.

like image 134
jan.supol Avatar answered Nov 15 '22 11:11

jan.supol