I have trouble understanding why this boolean b = new A() {} instanceof A;
is a valid statement and not boolean b = new A() instanceof A;
and why the former is true knowing that A is an abstract class.
The instanceof A
has nothing to do with whether the statement is valid or not, so your question is simpler if you leave it off from both statements:
A a = new A() {};
A a = new A();
The second statement isn't valid because A
is abstract and you can't call new
on any abstract class. If you could instantiate it, it would be an instance of A
, but you can't.
The first statement is valid because it creates an anonymous class that extends A
. This anonymous class isn't abstract (assuming A
doesn't define any abstract methods), and so it can be instantiated. It's an instance of A
because all subclasses are instances of their parent classes, abstract or not. It's basically a shortcut for saying:
public class AnonymousNameIDontCareAbout extends A {}
A a = new AnonymousNameIDontCareAbout();