Couldy you clarify why this works:
public abstract class AbstractClassCreationTest {
public void hello(){
System.out.println("I'm the abstract class' instance!");
}
public static void main(String[] args) {
AbstractClassCreationTest acct = new AbstractClassCreationTest(){};
acct.hello();
}
}
I suppose it contradicts to the specification where we can find:
It is a compile-time error if an attempt is made to create an instance of an abstract class using a class instance creation expression (§15.9).
You may have not noticed the difference:
new AbstractClassCreationTest(){};
versus
new AbstractClassCreationTest();
That extra {}
is the body of a new, nameless class that extends the abstract class. You have created an instance of an anonymous class and not of an abstract class.
Now go ahead an declare an abstract method in the abstract class, watch how compiler forces you to implement it inside {}
of anonymous class.
Notice the difference between:
AbstractClassCreationTest acct = new AbstractClassCreationTest(){};//case 1
NonAbstractClassCreationTest acct = new NonAbstractClassCreationTest();//case 2
case1 is an anonymous class definition. You are not instantiating an abstract class; instead you are instantiating a subType of said abstract class.
Here you are not creating the object of the AbstractClassCreationTest
class , actually you are creating an object of anonymous inner class who extends the AbstractClassCreationTest
class.This is because you have written new AbstractClassCreationTest(){} not new AbstractClassCreationTest()
You can know more about anonymous inner class from here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With