0

I have the following classes, representing webpages

App
Header
TableOperations

Header is common for all pages. So I can write:

class App extends Header

TableOperations class represent the operations that are related to table. All webpage has a table too, which has common operation. Now how do I design these 3 classes?

Now how App can use both classes methods?

I can't extend two classes in java. Any other way?

sriram
  • 8,562
  • 19
  • 63
  • 82

3 Answers3

3

Instead of using inheritance which should be used for objects with an is a relationship I would recommend composition. If you continue with the inheritance strategy you are likely to build a large class hierarchy where each class extends the other, which is not preferred.

class App{
    Header header = new Header();
    TableOperations operations = new TableOperations();
}
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
  • Thanks. If I use like this, then I need to create methods for table operations, right? Lets say I have method called `A` in `TableOperations`, then in `App` class, I need to have method `routeToA` which again invoke `TableOperations` `A` method, Right? – sriram Feb 13 '14 at 11:45
  • Yes or you could expose the table operations via a getter, such as `app.getTableOperations().a();` – Kevin Bowersox Feb 13 '14 at 11:46
3

Composition is your friend here. I would perhaps have your classes implement their specific interfaces. You can then use multiple interface inheritance in order to specify that App will implement functionality from your other 2 interfaces.

e.g.

class Header implements IHeader
class TableOperations implements ITableOperations

class App implements IHeader, ITableOperations {
   private final IHeader header = new Header();

   // method declared in IHeader
   public void methodForHeader() {
      header.methodForHeader();
   }
}

App would then delegate appropriately to the underlying implementations Header and TableOperations (most likely implemented as members)

etc...

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • I need to create instance variables for `Header` in `App` class, and call the header methods in the interface implementaion? – sriram Feb 13 '14 at 12:08
0

You can use Header use is-a i.e. part of structure and has common state for all hierarchy. And for operations has-a structure because the name operations says he has only operations, not state. But of course it depends your structure and requirements.

class App extends Header {
    TableOperations ops = new TableOperations();
}
Ashot Karakhanyan
  • 2,804
  • 3
  • 23
  • 28