According to Why should I prefer composition over inheritance?, I should prefer composition over inheritance. But what if I need to access the interface and class member in generic way? For example, I have parent class Shape and some child classes:
public class Shape{
private String customId;
public String getCustomId(){
return customId;
}
public void setCustomId(String aCustomId){
customId=aCustomId;
}
public abstract void draw();
}
public class Circle extends Shape{
@Override
public void draw(){
}
}
Some codes to use Shape interface
for(Shape s : shapeArray){
s.draw();
//access customId
if(s.getCustomId().equals(...)){
}
}
...
public class User{
private Shape shape;
public void printInfo(){
System.out.println("User Shape id:"+shape.getCustomId());
}
}
But it is violating composition over inheritance, so I change the inheritance to composition+interface:
public interface Shape{
String getCustomId();
void setCustomId(String aCustomId);
void draw();
}
public class Circle implements Shape{
private String customId;
public String getCustomId(){
return customId;
}
public void setCustomId(String aCustomId){
customId=aCustomId;
}
public void draw(){
}
}
I found composition is more unmaintainable in this case because:
when I add a new class, I need to copy and paste
private String customId; public String getCustomId(){ return customId; } public void setCustomId(String aCustomId){ customId=aCustomId; }
If I need to add a new child class member to Shape, I also need to edit all child class to add the class member as well as getter and setter into it
So my question is, do I need "composition over inheritance" if I need to access both the class member and methods in generic way?