title: Self Instantiation in Java
body: <p>How do I self-instantiate a Java class? I should not use any file other than its class file. Also assume that after the line where I initialized the NAME variable, they don't know the name of the class during compile-time.</p>
  
  <p>Example:</p>
  
  <pre><code>public class Foo implements Bar {
      public static final String NAME = "Foo";
  
      private void instantiate()  {
          Bar baz = (Bar)Class.forName(NAME).newInstance();
      }
      //...
  }
  </code></pre>
  
  <p>would be wrong since it needs to have another file called <code>Bar.java</code>. It should be:</p>
  
  <pre><code>public class Foo {
      /*
      Instantiate self...
      */
  }
  </code></pre>
  
  <p>I joined this programming challenges website where I am only allowed to submit one file per problem. I want to create a template class for all the classes that I'll be using for the challenges. So, what I have in mind is that I'll do this:</p>
  
  <pre><code>public class Foo {
      public static final String NAME = "Foo";
  
  
      public static void main (String[] args) throws IOException {
          //Instantiate self and call launch(args)
          Foo foo = new Foo();
          foo.launch(args);
          System.exit(0);
      }
  
      public void launch(String[] args) {
          //...Do actual code here
      }
  }
  </code></pre>
  
  <p>I want to only change the class name and the NAME variable and not have to change the way I instantiate the class everytime I use the template class. With the current setup I have, I'll have to edit the line: <code>Foo foo = new Foo();</code> and maybe the line below that. </p>
  
  <p>You might also be wondering why I have to call <code>launch()</code> and not do everything inside the main method. That's just something I got from my Java instructor. It's also since I can't use non-static methods inside the <code>main()</code> method.</p>