-1

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?

Ivar
  • 6,138
  • 12
  • 49
  • 61
Pizza eu
  • 1,419
  • 1
  • 14
  • 27
  • 2
    newObj is an instance of anonymous class that extends Object class. – ChipLimo Mar 05 '19 at 08:09
  • This is not Java. It might be JavaScript. – user207421 Mar 05 '19 at 08:38
  • @user207421 [It compiles fine](https://tio.run/##TY2xDoMwDERn8hUWEwyN1Bn1E6oOjBWDCRFKGgLChqqq@PbUiFbqYp/u3dkeVzz57pHStLTBGTABieCKLsJbZV@TGFnWOroOBkFFzbOL/b0BnHsq92S24gzRPm@th8suQJQ1DMWBf6eOJpCEcrbEefUHXWRwQs67uVVKZv0itoMeF9aTNDnE4viiqZTUpraUPg). – Ivar Mar 05 '19 at 08:47

1 Answers1

1

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
Andrianekena Moise
  • 1,018
  • 7
  • 16
  • 1
    That is the only really interesting part: because of `var`, the compiler can now "track" that you are extending Object, so when you put a new method into that class, you can later invoke it. – GhostCat Mar 05 '19 at 08:23