I have two classes called "J48Tree" and "RandomTree". They are both subclasses of "AbstractTree".
"J48Tree" and "RandomTree" have a method called "graph()", other subclasses of "AbstractTree" don‘t have this method.
These classese above and the graph() method come from exsiting API. So I dont need to rewrite them.
Now I want to create a new class called “Visualization”. This class can receive "J48Tree" and "RandomTree" as genetic input data. And then run their "graph()" method.
I tried
public class Visualization <T super J48Tree>
and
public class Visualization <T extends AbstractTree>
But it doesn't work.
How do I solve this problem?
Thanks in advance.
As Florian says, you want to create an interface Graphable
and make both J48Tree
and RandomTree
implement it.
public interface Graphable {
void graph();
}
public class J48Tree extends AbstractTree implements Graphable {
@Override
public void graph() {
// implementation
}
}
public class RandomTree extends AbstractTree implements Graphable {
@Override
public void graph() {
// implementation
}
}
public class Visualization {
private Graphable graphable;
public void setGraphable(Graphable graphable) {
this.graphable = graphable;
}
public void graph() {
this.graphable.graph();
}
}
Then, you can set the Graphable
implementation on Visualization
class by calling setGraphable
.
EDIT
From your comment I understand you are not capable of making neither J48Tree
nor RandomTree
implement the Graphable
interface (that's the only change on the classes you have to make). In this case, you should 'wrap' an instance of each class into another class, a wrapper, that implements Graphable
.
public interface Graphable {
void graph();
}
public class J48TreeWrapper implements Graphable {
private final J48Tree j48Tree;
public J48TreeWrapper(J48Tree j48Tree) {
this.j48Tree = j48Tree;
}
@Override
public void graph() {
this.j48Tree.graph();
}
}
public class RandomTreeWrapper implements Graphable {
private final RandomTree randomTree;
public RandomTreeWrapper(RandomTree andomTree) {
this.randomTree = randomTree;
}
@Override
public void graph() {
this.randomTree.graph();
}
}
public class Visualization {
private Graphable graphable;
public void setGraphable(Graphable graphable) {
this.graphable = graphable;
}
public void graph() {
this.graphable.graph();
}
}
Now, you will first have to create an instance of J48TreeWrapper
that 'wraps' a J48Tree
, and then you call setGraphable
using it (same with RandomTreeWrapper
).
public static void main(String[] args) {
J48TreeWrapper wrapper = new J48TreeWrapper(new J48Tree());
Visualization visualization = new Visualization();
visualization.setGraphable(wrapper);
visualization.graph();
}