javainner-classesanonymous-inner-class

Inner class problem - Java unable to find "InnerClass2" when Nested within Main


Noob here. I have tried the following code, but it appears that Java cannot find InnerClass2 when nested. I could not find any guide on how to fix this issue. I also tried InnerClass2 in = Main.new InnerClass2(); but it did not work either. Thoughts?

public class Main {
  public static void main(String[] args) {
   InnerClass2 in = new InnerClass2();
   class InnerClass2 {
     InnerClass2(){
     }
    }
   }
  }

Solution

  • You can't declare a class within a method. You could instead declare it inside the Main class:

    public class Main {
      public static class InnerClass2 {
        // class details
      }
      public static void main(String[] args) {
        InnerClass2 in = new InnerClass2();
      }
    }