title: Java Object Scope
body: <p>I am trying to create an object based on a condition, therefore the object creation is within the conditional's scope, however I need to see the object outside of that scope. I thought adding it to a Map would work, but it doesn't. Consider the following example:</p>
  
  <p><strong>TestModel.java</strong></p>
  
  <pre><code>public class TestModel {
  private String text;
  public void setText(String text){
  this.text = text;}
  public String getText(){
  return this.text;}
  }
  </code></pre>
  
  <p><strong>ScopeTest.java</strong></p>
  
  <pre><code>import java.util.*;
  class ScopeTest {
  
  public static void main(String[] args) {
  
  TestModel testModel;
  Map&lt;String, Object&gt; myModel = new HashMap&lt;String, Object&gt;();
  
  for (int i=1; i&lt;2; i++){ // if a certain condition is met, create an object as below
      testModel = new TestModel();
      testModel.setText("test text");
      myModel.put("test", testModel);
      }
  
  for (Map.Entry&lt;String, Object&gt; entry : myModel.entrySet()) {
      String key = entry.getKey();
      Object value = entry.getValue();
      System.out.println("key=" + key); // I can see the key value
      System.out.println("value.getText()=" + value.getText()); // but can't see testModel object. I am not sure how to resolve.
  }
  }
  }
  </code></pre>
  
  <p>cheers,</p>
  
  <p>Geofrey Rainey.</p>