Witscale Test Center

4.7 Anonymous inner class > 4.7.1 Anonymous class implementing an interface


4.7.1 Anonymous class implementing an interface

Besides extending class, an anonymous class may implement an interface. Anonymous class implementing an interface is also declared and constructed at the same time. Let us consider a simple interface:

 

interface Paddleable {

 void paddle();

}

 

An anonymous class implementing this interface may be declared and constructed as:

 

Paddleable bike = new Paddleable() {

    public void paddle() {

           System.out.println(“paddling a bike”);

    }

};

 

The anonymous class can either extend a class or implement an interface but cannot do both at the same time. For example, an anonymous inner class can either extend the Bicycle class or implement the Paddleable interface, but cannot do both at the same time.