I am developing a simple game. I created a Maze class which contains methods and algorithms for creating / modifying / solving mazes. I also created a GraphicalMaze class, which should only contain a paint method to draw the maze on a JPanel.
At this point, i have to decide if:
GraphicalMazeshould extendsMaze, with aJPanelas member variable (inheritance)
or
GraphicalMazeshould extendsJPanel, withMazeas member variable (composition)
This problem recurs every time i have to create ‘gui’ objects from ‘abstract’ ones.
I am interested in your opinions, and i want to understand what is the ‘right’ way to proceed.
This is not the easiest or most objective question to answer. There are some who tend to say you should favor composition over inheritance in most cases. I would say, think about your objects and how they really relate to each other. In this case, remember that inheritance represents an is-a relationship, whereas composition represents a has-a.
So, the question becomes, is-a GraphicalMaze a Maze? Or is it the representation of a maze? I would argue its the latter. Which of course means you would be using composition instead of Inheritance to represent it.