Search code examples
javaanonymous-class

Creating object with new Object{}


Could you please explain how this construction actually works and what does it mean?

var newObj = new Object () {
  public String s = "test";
  public int i = 1;
};

What's the class of newObj and how it was created?


Solution

  • The class of the newObj is an Anonymous Inner Class. Here you define this anonymous inner class inside the curly brace {}.

    An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overloading methods of a class or interface, without having to actually subclass a class.

    Also, the newObj reference refers, not to an instance of Object but to an instance of an anonymous subclass of Object.