Hi j rab,
First of all, a warm welcome to CodeRanch!
j rab wrote:I know abstract classes can't be instantiated and I thought the same would apply for abstract inner classes but I was wrong. Can someone explain to me why you can instantiate an abstract inner class?
First of all, inner classes are not on the
OCAJP certification exam. Secondly there is no difference between abstract top-level classes and abstract inner (nested) classes: both can
not be instantiated. This is clearly illustrated in the following code snippet
Both
line1 (top-level class) as
line2 (inner class) will result in a compiler error because an abstract class can't be instantiated. It doesn't matter if it's a top-level or an inner class.
But now you are probably wondering why your code snippet compiles successfully

Here's the answer: you don't have instantiated an abstract inner class (because that's not allowed as illustrated in the previous code snippet), but you have created an anonymous class and created an instance of this annonymous class. And again that's allowed for both top-level classes and inner classes. Here is again an illustrative code example using the same classes
This code snippet compiles successfully (without any compiler errors)! But although it seems you are instantiating abstract (inner) classes, that's
not the case. And that's very important to notice (and remember)! On
line1 you are creating an anonymous class of the (top-level) class
Animal and instantiating this anonymous class, all in 1 statement. On
line2 the same happens: you create an anonymous class of the (inner) class
Engine and instantiate this anonymous class, again all in 1 statement. And that's exactly what you have done in your code snippet as well.
So this code snippet is equivalent to the above code snippet and illustrates what's actually happening behind the scenes
Hope it helps!
Kind regards,
Roel
Disclaimer: inner (nested) classes are not on the OCAJP certification exam, it's an exam objective of the OCPJP certification exam. So if you are preparing for the OCAJP certification exam, you don't have to worry about that weird looking syntax
