[英]Java: how to create instances of two different classes in a third class and pass references to each other through the constructors
[英]How do I create a new class to process two other classes in Java?
我有兩個類,分別為“ J48Tree”和“ RandomTree”。 它們都是“ AbstractTree”的子類。
“ J48Tree”和“ RandomTree”具有稱為“ graph()”的方法,“ AbstractTree”的其他子類沒有此方法。
以上這些類和graph()方法來自現有的API。 所以我不需要重寫它們。
現在,我想創建一個名為“ Visualization”的新類。 此類可以接收“ J48Tree”和“ RandomTree”作為遺傳輸入數據。 然后運行他們的“ graph()”方法。
我試過了
public class Visualization <T super J48Tree>
和
public class Visualization <T extends AbstractTree>
但這是行不通的。
我該如何解決這個問題?
提前致謝。
您可以看一下策略設計模式: http : //www.tutorialspoint.com/design_pattern/strategy_pattern.htm
尋找適合您提到的場景,因為需要根據傳遞的輸入對象在運行時確定行為(方法)。
正如Florian所說,您想創建一個Graphable
接口,並使J48Tree
和RandomTree
實現它。
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();
}
}
然后,可以通過調用setGraphable
在Visualization
類上設置Graphable
實現。
編輯
根據您的評論,我知道您無法使J48Tree
和RandomTree
實現Graphable
接口(這是您必須對類進行的唯一更改)。 在這種情況下,您應該將每個類的實例“包裝”到另一個實現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();
}
}
現在,你必須首先創建一個實例J48TreeWrapper
是“包裝”一個J48Tree
,然后調用setGraphable
使用它(與相同RandomTreeWrapper
)。
public static void main(String[] args) {
J48TreeWrapper wrapper = new J48TreeWrapper(new J48Tree());
Visualization visualization = new Visualization();
visualization.setGraphable(wrapper);
visualization.graph();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.