Niketh Kumar
Niketh Kumar

Reputation: 159

Inner classes inside a instance method

I have seen an unusual occurrence. Please help me how to instantiate a class which is written inside a method. The below program compiled successfully in Netbeans

  class OuterClass
    {
      int instanceVar;
      void InstanceMethod()
       {
          class InnerClass
           {
             int innerClassVar;
           }
       }
    }

Upvotes: 3

Views: 108

Answers (3)

Behe
Behe

Reputation: 7950

Just to add: These are called Local Classes. You instantiate them like "normal" classes in your method, as pointed out in morgano's answer

Upvotes: 4

Joop Eggen
Joop Eggen

Reputation: 109613

Can only be used inside the method, and most often should be a static class.

Upvotes: 1

morgano
morgano

Reputation: 17422

just do it like any other object:

class OuterClass
{
  int instanceVar;
  void InstanceMethod()
   {
      class InnerClass
       {
         int innerClassVar;
       }

       //...

       InnerClass myInstance = new InnerClass();
   }
}

Upvotes: 8

Related Questions