简体   繁体   English

从Java中的子类构造函数填充父类中的哈希图

[英]Fill a hashmap in superclass from subclass constructor in Java

I have an abstract superclass that is set up like this in JavaFX: 我有一个在JavaFX中这样建立的抽象超类:

abstract class View {
protected static HashMap<String, View> viewMap;
View(){
    viewMap = new HashMap<String, View>();
}
public static void addMap(String key, View value){
    viewMap.put(key, value);
}

This super class includes the method: 该超类包括以下方法:

public static VBox goToView (final String view){
    return viewMap.get(view).getView();
}

Then I have some subclasses that represents scenes I want to load set up like this: 然后,我有一些子类来表示要加载的场景,如下所示:

public class SceneA extends View {

private static String title;

public ViewA() {

    title = "TitleA";

    super.addMap(title, this);
}

public VBox getPane(){
      //code that will load for this scene
}

Subsequent subclass scenes are set up the same way. 随后的子类场景以相同的方式设置。 Then in the main program I call like this: 然后在主程序中我这样调用:

public class OrganizationMenu {

private Stage organization;
private static BorderPane border;

public OrganizationMenu() {

    stage = new Stage();

    border = new BorderPane();
    border.setCenter(View.goToView(ViewA.getTitle()));

This works great for the first view, but any subsequent views aren't being added to the HashMap at the superclass. 这对于第一个视图非常有用,但是不会在超类的HashMap中添加任何后续视图。 I can't understand why. 我不明白为什么。 Even if I save the ViewA code as ViewB, just changing the references, it doesn't fill the map. 即使将ViewA代码另存为ViewB,只是更改引用,它也不会填满地图。 Why would this work for one and not additional views? 为什么要为一个视图而不是其他视图工作?

What i understood is you have an Abstract class View, this class contains a static HashMap viewMap. 我了解的是您有一个Abstract类View,该类包含一个静态HashMap viewMap。 This abstract class has some subclasses and each time a subclass is instantiated, you want that subclass get added to the viewMap object of super class. 这个抽象类具有一些子类,并且每次实例化一个子类时,您都希望将该子类添加到超类的viewMap对象中。

If i am right then the constructor in the super class View is the problem. 如果我是对的,那么超类View中的构造函数就是问题。 Everytime a subclass gets instantiated, the viewMap is pointing to a new HaspMap object as the constructor of subClass 每次实例化一个子类时,viewMap都将指向一个新的HaspMap对象作为子类的构造函数。

Please remove the constructor code and try like this: 请删除构造函数代码,然后尝试如下操作:

abstract class View {

protected static HashMap<String, View> viewMap = new HashMap<String, View>();

public static void addMap(String key, View value) {
    viewMap.put(key, value);
}

Hope this works. 希望这行得通。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM