Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applicable Design pattern

I have this working hierarchy already and the program runs as expected. Basically I have abstracted everything in a Base class and all other subclass adding their own methods.

abstract Class Base{
}

class A extends Base{
    //new methods
}

class B extends Base{
    //new methods
}

everything looks good until later (errr...new requirements) I realize I need to have a new class (lets call this class C) that extends both class A and B. Now, in java its not possible to extend two concrete class.

class C extends A, B{
    //new methods
}

I need both of the methods and variables in class A and class B but I dont know how to do this? Any hints on how do I do this change? I am not that good in design pattern so i thought of asking it here.

Thanks

UPDATE This is actually a JSF Managed Bean wherein I abstracted everything in a Base Managed Bean and all other subclass overriding/adding their own implementations on top of the base managed bean. There is just a new requirement that was added wherein I needed the functionality of both subclasses (A and B) into a new subclass (C)

like image 626
Mark Estrada Avatar asked Apr 16 '13 10:04

Mark Estrada


2 Answers

Refactor your code and make A and B and Base interfaces instead of classes and use interface inheritance instead of implementation inheritance.
Then you can implement both A and B (this is how multiple inheritance is supported in Java)

like image 185
Cratylus Avatar answered Sep 28 '22 08:09

Cratylus


Either use composition or use inner class.

class C extends A {
   B b = ... // this is one option

   class D extends B {
     // this is another option 
   }  
}
like image 42
Sudhanshu Umalkar Avatar answered Sep 28 '22 08:09

Sudhanshu Umalkar