Problem with java interface

The code: -

10. interface Foo { int bar(); }
11. public class Sprite {
12.     public int fubar( Foo foo) { return foo.bar(); }
13.     public void testFoo() {
14.         fubar(
15.             new Foo() { public int bar(){ return 1; } }
16.         );
17.     }
18. }

-Am cannot understand from line 14 to 16. Because I have never seen such a thing in one method inside. Any authority, please explain 14-16 lines?

+3
source share
3 answers

The string is invalid. It should have a space between "new" and "Foo":

new Foo() { public int bar(){ return 1; } }

This creates an instance of the anonymous type that implements Foo. See Java in a nutshell: Anonymous classes (section 3.12.3 describes the syntax).

Anonymous classes are often widely used with event listeners. See Swing Trail: Inner Classes and Anonymous Inner Classes (but ignore the Inner Classes discussed at the top of this section;)

Happy coding.


:

14 - fubar ( public int fubar(Foo foo)). , new ... - ( ), ( ) fubar. - . :

Foo aNewFoo = new Foo() { ... };
fuubar(aNewFoo);

, .

+3

. , , , new Foo() { ... }. Foo. :

interface Foo { int bar(); }
public class Sprite {
    public int fubar( Foo foo) { return foo.bar(); }
    public class MyFoo implements Foo {
        public int bar() { return 1; }
    }
    public void testFoo() {
        fubar(
            new MyFoo()
        );
    }
}

( , new Foo .)

+3

He called an anonymous inner class. You create an implementation Fooon the fly instead of writing a named class.

Here is a potentially useful SO question about what they are and when you can use them.

+2
source

All Articles