I want to avoid redefining accept() in every class extending Containers, so I defined it in containers. Java won't compile it except if I create a function visit(Container cont) in my visitor. I thought that by doing this, I would force the compilation but the visit(Container cont) would never be used ... because Java takes the lowest class, but it didn't.
Result : I got an infinite recursive loop using every time visit(Container cont)...
Can you explain me why and how to fix it ( without defining accept in every container and making FinderPackBuilder an interface ).
Thank you !
EDIT : The result of element.getClass() is never a Container, I tested it.
public abstract class FinderPackBuilderVisitor {
abstract public Document visit (Module module);
abstract public Document visit (Dashboard dashboard);
abstract public Document visit (Section section);
abstract public Document visit (Metric metric);
// The last visit method is here to ensure that all containers can use visit. It will never be used since Container is not Instantiable.
// Another alternative would be to make this an interface and delete this method but we would have to dupliacte code in every instantiable class.
Document visit (Container element){
System.out.println(element.getClass());
System.out.println("This function shouldn't be taken");
return visit(element);
}
public abstract class Container<T extends Container> {
protected String name;
protected ArrayList<T> children;
public Container(String n, ArrayList<? extends T> c){
name = n;
children = new ArrayList<T>();
for (T child : c){
children.add((T)child.getCopy());
}
}
Document accept(FinderPackBuilderVisitor visitor){
for (T child : children){
child.accept(visitor);
}
System.out.println(this.getClass());
return visitor.visit(this);
}
abstract Container<T> getCopy();
}