Search code examples
javajavafxsubclassabstractsuperclass

Fill a hashmap in superclass from subclass constructor in Java


I have an abstract superclass that is set up like this in 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. I can't understand why. Even if I save the ViewA code as ViewB, just changing the references, it doesn't fill the map. Why would this work for one and not additional views?


Solution

  • What i understood is you have an Abstract class View, this class contains a static 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.

    If i am right then the constructor in the super class View is the problem. Everytime a subclass gets instantiated, the viewMap is pointing to a new HaspMap object as the constructor of subClass

    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.