I'm trying to translate JavaScript code into Java code.
In JavaScript, interfaces can have attributes, and an interface can extend multiple interfaces:
interface Interface1 {
name?: string
age?: number
}
interface Interface2 {
id?: string
}
interface InterfaceCombination extends Interface1, Interface2 {
position?: string
}
I want to translate this JavaScript code into Java code. I have several ideas, but I don't know if they are good designs.
First idea: classes & delegation
Since Java interfaces only have final static
attributes, I choose classes to maintain those attributes:
public class Class1 {
private String name;
private Number age;
public String getName();
public void setName(String name);
... // getter & setter for age
}
public class Class2 {
private String id;
... // getter & setter for id
}
However, there is the problem. A Java class can only extends one class, so I choose to use delegation:
public class ClassCombination {
private Class1 class1;
private Class2 class2;
private String position;
public String getName() {
return class1.getName();
}
... // getters & setters
}
This would lead to a lot of repeated work when the delegation hierarchy is deep. I tried to use @Delegate annotation in lombok, but this is experimental and doesn't support recursive delegation.
Second idea: interface & getters & setters
Though a Java class can only extend one class, a Java interface can extend multiple interfaces.
public interface Interface1 {
public String getName();
public void setName();
... // getter & setter for age
}
public interface Interface2 {
... // getter & setter for id
}
public interface InterfaceCombination extends Interface1, Interface2 {
... // getter & setter for position
}
This solution would lead to a heavy work on writing getters and setters in interfaces. And I cannot use lombok to automatically generate getters and setters in interfaces.
Is there any solution more elegant and easier to implement?