102

How can an anonymous class implement two (or more) interfaces? Alternatively, how can it both extend a class and implement an interface? For example, I want to create an object of anonymous class that extends two interfaces:

    // Java 10 "var" is used since I don't know how to specify its type
    var lazilyInitializedFileNameSupplier = (new Supplier<String> implements AutoCloseable)() {
        private String generatedFileName;
        @Override
        public String get() { // Generate file only once
            if (generatedFileName == null) {
              generatedFileName = generateFile();
            }
            return generatedFileName;
        }
        @Override
        public void close() throws Exception { // Clean up
            if (generatedFileName != null) {
              // Delete the file if it was generated
              generatedFileName = null;
            }
        }
    };

Then I can use it in a try-with-resources block as AutoCloseable as lazily-initialized utility class:

        try (lazilyInitializedFileNameSupplier) {
            // Some complex logic that might or might not 
            // invoke the code that creates the file
            if (checkIfNeedToProcessFile()) {
                doSomething(lazilyInitializedFileNameSupplier.get());
            }
            if (checkIfStillNeedFile()) {
                doSomethingElse(lazilyInitializedFileNameSupplier.get());
            }
        } 
        // By now we are sure that even if the file was generated, it doesn't exist anymore

I don't want to create an inner class because I'm absolutely sure that this class won't be used anywhere except the method I need to use it in (and I also might want to use local variables declared in that method that might be of var type).

izogfif
  • 6,000
  • 2
  • 35
  • 25

6 Answers6

104

Anonymous classes must extend or implement something, like any other Java class, even if it's just java.lang.Object.

For example:

Runnable r = new Runnable() {
   public void run() { ... }
};

Here, r is an object of an anonymous class which implements Runnable.

An anonymous class can extend another class using the same syntax:

SomeClass x = new SomeClass() {
   ...
};

What you can't do is implement more than one interface. You need a named class to do that. Neither an anonymous inner class, nor a named class, however, can extend more than one class.

aspiring_sarge
  • 2,355
  • 1
  • 25
  • 32
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • 1
    I don't think the second expression is correct. You've already declared the name of the class as SomeClass, it's not anonymous anymore. Check out this link http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm When you "new" an interface, an anonymous class is created by extending "Object" class and implementing that interface. But while you are "newing" a class with the first expression you wrote, an anonymous class (In fact, it's an instance of that anonymous class is created) will be create by extending that class. – lixiang May 02 '12 at 03:49
  • 8
    @youmiss: The 2nd expression will create an instance of an anonymous class which extends `SomeClass`. It is still anonymous, due to the `{...}`. – skaffman May 02 '12 at 09:33
  • 1
    I see, I overlooked the {...}. – lixiang May 02 '12 at 10:57
37

An anonymous class usually implements an interface:

new Runnable() { // implements Runnable!
   public void run() {}
}

JFrame.addWindowListener( new WindowAdapter() { // extends  class
} );

If you mean whether you can implement 2 or more interfaces, than I think that's not possible. You can then make a private interface which combines the two. Though I cannot easily imagine why you would want an anonymous class to have that:

 public class MyClass {
   private interface MyInterface extends Runnable, WindowListener { 
   }

   Runnable r = new MyInterface() {
    // your anonymous class which implements 2 interaces
   }

 }
extraneon
  • 23,575
  • 2
  • 47
  • 51
  • I like this answer because it's google friendly for people looking for implementing 2 or more interfaces in anon implementation. – L. Holanda Jun 25 '18 at 17:55
27

I guess nobody understood the question. I guess what this guy wanted was something like this:

return new (class implements MyInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }
});

because this would allow things like multiple interface implementations:

return new (class implements MyInterface, AnotherInterface {
    @Override
    public void myInterfaceMethod() { /*do something*/ }

    @Override
    public void anotherInterfaceMethod() { /*do something*/ }
});

this would be really nice indeed; but that's not allowed in Java.

What you can do is use local classes inside method blocks:

public AnotherInterface createAnotherInterface() {
    class LocalClass implements MyInterface, AnotherInterface {
        @Override
        public void myInterfaceMethod() { /*do something*/ }

        @Override
        public void anotherInterfaceMethod() { /*do something*/ }
    }
    return new LocalClass();
}
thiagoh
  • 7,098
  • 8
  • 51
  • 77
16

Anonymous classes always extend superclass or implements interfaces. for example:

button.addActionListener(new ActionListener(){ // ActionListener is an interface
    public void actionPerformed(ActionEvent e){
    }
});

Moreover, although anonymous class cannot implement multiple interfaces, you can create an interface that extends other interface and let your anonymous class to implement it.

MByD
  • 135,866
  • 28
  • 264
  • 277
3
// The interface
interface Blah {
    void something();
}

...

// Something that expects an object implementing that interface
void chewOnIt(Blah b) {
    b.something();
}

...

// Let's provide an object of an anonymous class
chewOnIt(
    new Blah() {
        @Override
        void something() { System.out.println("Anonymous something!"); }
    }
);
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

An anonymous class is extending or implementing while creating its object For example :

Interface in = new InterFace()
{

..............

}

Here anonymous class is implementing Interface.

Class cl = new Class(){

.................

}

here anonymous Class is extending a abstract Class.

Cthulhu
  • 5,095
  • 7
  • 46
  • 58