Search code examples
javaoopinterfacezkextends

Java multiple extends Zk Component became very verbose


i dont really want to make this question. maybe because is some kind silly but the verbosity give me the encorague to do so... so i want you be kindle with me.. thanks.

i have a simple interface with a bunch of methods.

public interface MyInterface
{
    public Integer getSolution();
    public void setSolution(final Integer a);
    public void markAsSent(final boolean sent);
    public boolean wasSent();
    ......
    ......
 }

we are extending the ZK components like Textbox,Datebox,Bandbox,Decimalbox

we have something like

 public class CustomTextBox  extends Textbox implements MyInterface
 {}//we add the implementations of the methods... 

the problems arise when i need to extends another ZK components Datebox,Bandbox,Decimalbox and so on.

the methods implementation of the MyInterface is the same for ALL.

only changes the extends of the class like this....

public class CustomBandBox  extends Bandbox implements MyInterface
public class CustomComboBox  extends Combobox implements MyInterface
public class CustomDecimalBox  extends Decimalbox implements MyInterface

as i hate the verbosity very much i would like to create a class which the implementations of the MyInterface and also extends the Zk Components as Java not allows multiple inheritance how can i do something like this..

any workaround like using Generics or any help is hugely appreciate..

we are using Java 7 i think this can be solved in Java 8 with defaults methods but i am stuck still with 7


Solution

  • You should use composition in that case. Consult the Strategy Design Pattern, perhaps from one of my favorite DP book Head First Design Patterns. It is described in the first chapter as a design principle, that instead of the overuse of inheritance, you should often consider composition.

    The behavior declared in MyInterface should be impemented in an onw class and reached by composition:

        public class MyImplementation implements MyInterface {
           // perhaps you need a reference to the ZK Component here
           private Component comp;
           public MyImplementation(Component comp){
             this.comp = comp;
           }
        }
    
        public class CustomBandBox  extends Bandbox implements MyInterface {
            private MyImplementation impl = new MyImplementation(this);
    
            public Integer getSolution(){
              return impl.getSolution();
            }
        }