Declaring a method when creating an object
Java is statically typed. When you say object.a()
it is looking for the method a
in the Object
class which is not present. Hence it does not compile.
What you can do is get the method of object
using reflection as shown below :
Object object = new Object() {
public void a() {
System.out.println("In a");
}
}
Method method = object.getClass().getDeclaredMethod("a");
method.invoke(object, null);
This would print
In a
java.lang.Object
has no a
methods declared (2), while the anonymous class returned by the class instance creation expression new Object() { public void a() {} }
does (1).
Use Java 10's local variable type inference (var
) to make the second option as valid as the first one.
var object = new Object() {
public void a() {}
};
object.a();
In the 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 the first option, you basically create new object of anonymous class that extends java.lang.Object
. That anonymous class has the additional method a()
, which is why you can call it.