1

When we create an anonymous class, like

Employee emp = new Employee() {
  void get() {
    //Some body
  }
  void put() {    
    //Some body
  }
};
emp.set();
emp.get();

the object reference emp refers to the object of the above anonymous inner class. We can also create another anonymous class whose object can be referred by the same object reference, like

emp = new Employee() {
      void x() {
        //Some body
      }
      void y() {    
        //Some body
      }
    };
    emp.x();
    emp.y();

But is there any way of creating another object for the same anonymous class? Is it possible to create a new object for an existing anonymous class, if needed?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Ishwar
  • 338
  • 2
  • 11

1 Answers1

3

As a general rule of thumb - if you want more than one instance of the same anonymous class, chances are it shouldn't be anonymous - just make it a plain old named class and instantiate as many objects of it as you want.

One dirty trick you could use, though, is accessing the instance's getClass() and using reflection to instantiate a new instance:

Employee emp2 = emp.getClass().newInstance();
Mureinik
  • 297,002
  • 52
  • 306
  • 350