title: Declaring an instance of a class inside that class
body: <p>This code shows error at run time:</p>
  
  <pre><code>class Animal {
      Animal object1 = new Animal();
  
      public static void main(String[] args) {     
          Animal obj = new Animal();
      }
  }
  </code></pre>
  
  <p>This is slightly different code with <code>Animal obj = new Animal();</code> this line from main 
  method commented out. this code shows no run time error. </p>
  
  <pre><code>class Animal {
      Animal object1 = new Animal();
  
      public static void main(String[] args) {     
          // Animal obj = new Animal();
      }
  }
  </code></pre>
  
  <p>How is this caused and how can I solve it? I am using command prompt to run this code.</p>