0

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?

puraVida
  • 43
  • 4
  • 2
    `View(){ viewMap = new HashMap(); }` you are creating a new `Map` every time you are instanciating `View` or one of its sub-classes. – Florent Bayle Apr 27 '15 at 12:22
  • 1
    initializing static fields from instance methods or constructors is a huge design small. A static variable is shared by ALL instances of the class. In fact, non-final static variables are, by themselves, a design smell. – JB Nizet Apr 27 '15 at 12:31
  • thank you... this makes perfect sense... but i'm kind of new so sometimes these things don't jump out right away ;) – puraVida Apr 27 '15 at 16:05

1 Answers1

1

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.

Ravi Ranjan
  • 740
  • 2
  • 10
  • 31