Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance of an abstract class [duplicate]

Tags:

java

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).

like image 376
Kifsif Avatar asked Aug 26 '13 07:08

Kifsif


Video Answer


3 Answers

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.

like image 87
S.D. Avatar answered Oct 14 '22 22:10

S.D.


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.

like image 41
rocketboy Avatar answered Oct 14 '22 23:10

rocketboy


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

like image 38
Krushna Avatar answered Oct 14 '22 22:10

Krushna