Michał Szewczyk
Michał Szewczyk

Reputation: 8168

Is it possible to declare anonymous class as abstract?

I am trying to find out, if it is possible to create anonymous inner class as abstract.
I thought, that it doesn't make sense because I am trying to create instance of the abstract class, but the message from compiler confused me:

Class 'Anonymous class derived from Test' must either be declared abstract or implement abstract method 'method()' in Test

Code:

abstract class Test{
    abstract void method();
}
Test o = new Test(){};


If it is possible to declare anonymous class as abstract, please let me know how to do that.
I would be greatful for answer.

Upvotes: 0

Views: 1060

Answers (3)

Holly
Holly

Reputation: 1495

As quoted by Andy Turner the answer to your question is NO.

However I think you wanted to know something different.

Why do you get this compiler message?

Well the compiler is a bit misleading here. It offers two possible solutions based on that you are declaring a class (that anonymous class) and then also want to create an instance of that class:

  1. make the derived class (which an anonymous class always is) abstract, this is fine for normal and inner classes but it is not possible for anonymous classes, so the compiler should not suggest it in the first place
  2. implement all methods and have no abstract methods in your anonymous class declaration

So to solve your actual problem: simply implement method() so your anonymous class declaration contains no more abstract methods

abstract class Test{
    abstract void method();
}
Test o = new Test()
{
  void method()
  {
    // do something 
  };
};

Now everything is declared and the compiler should not complain any more.

Upvotes: 0

M Sach
M Sach

Reputation: 34424

you can't and does not make sense to declare anonymous class as abstract class as anonymous are used as local class only once.

i think you are getting this error because of similar issue Class must either be declared abstract or implement abstract method error

Upvotes: 0

Andy Turner
Andy Turner

Reputation: 140318

See JLS Sec 15.9.5 (emphasis mine):

15.9.5. Anonymous Class Declarations

An anonymous class declaration is automatically derived from a class instance creation expression by the Java compiler.

An anonymous class is never abstract (§8.1.1.1).

An anonymous class is always implicitly final (§8.1.1.2).

An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1).

Upvotes: 6

Related Questions