9

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

Kifsif
  • 3,477
  • 10
  • 36
  • 45

4 Answers4

21

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.

S.D.
  • 29,290
  • 3
  • 79
  • 130
7

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.

rocketboy
  • 9,573
  • 2
  • 34
  • 36
  • When I declare an anonymous class, however I don't use an abstract class. I don't know if possible do it. I can't find anything on web and in your link there's no reference about link between abstract and anonymous class. – Joe Taras Aug 26 '13 at 07:25
3

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

Krushna
  • 5,059
  • 5
  • 32
  • 49
0

An abstract class cannot instantiated.

You must create an extension class extends an abstract class and so istantiated this new class.

public abstract class AbstractClassCreationTest {

    public void hello(){
        System.out.println("I'm the abstract class' instance!");
    }
}

public class MyExtClass extends AbstractClassCreationTest() {
}

public static void main(String[] args) {
    MyExtClass acct = new MyExtClass(){};
    acct.hello();
}

I post this. Can be useful for you. Have a nice day

Joe Taras
  • 15,166
  • 7
  • 42
  • 55