Adam Arold
Adam Arold

Reputation: 30528

Can I implement an interface while instantiating an anonymous class?

Suppose I have an abstract class FactorizedDialog. It looks like this (please note that this is just some dummy example)

public abstract class FactorizedDialog extends Dialog {

  public abstract void myMethod();
} 

Now I can do something like this:

FactorizedDialog dialog = new FactorizedDialog() {

            @Override
            public void myMethod() {
                // implementation here
            }
}

As you may have guessed I extend Dialog (which is in fact an abstract class) only to add a method to it so I can override it when I create an anonymous class. Is it possible to implement an interface in java while I instantiate Dialog instead of using my derived abstract class?

Upvotes: 0

Views: 243

Answers (2)

adarshr
adarshr

Reputation: 62583

If you mean the below where Dialog is an interface, then yes it can be done.

Dialog dialog = new Dialog() {

    @Override
    public void myMethod() {
    }
}

Of course then the declaration of myMethod should go into the Dialog interface.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500215

No, when you specify the superclass of an anonymous inner class you can either specify a normal class to extend or an interface, but not both. The syntax shown in section 15.9 of the JLS simply doesn't allow for both.

Upvotes: 1

Related Questions