Declaring a method when creating an object

  • A+

Why first way is correct, but second isn't?

First way:

new Object() {     public void a() {         /*code*/     } }.a(); 

Second way:

Object object = new Object() {     public void a() {         /*code*/     } };  object.a(); 

And where can I find more information about it?


In second option you assign your new object to a reference of type Object because of this only methods defined in java.lang.Object could be called on that reference.

And in first option you basically create new object of anonymous class that extends java.lang.Object. And that anonymous class has additional method a() that is why you can call it.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: