mriganka3
mriganka3

Reputation: 687

java interface problem

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 not being able to understand from line number 14 to 16.because I have never seen such thing fubar inside one method.Will any body please explain 14-16 no line?

Upvotes: 3

Views: 1179

Answers (3)

user166390
user166390

Reputation:

The line is wrong. It should have a space between "new" and "Foo":

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

This creates an instance of an anonymous type which implements Foo. See Java in a Nutshell: Anonymous Classes (section 3.12.3 covers the syntax).

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

Happy coding.


For comment:

Line 14 is the start of the method call for fubar (which is defined above as public int fubar(Foo foo)). Note that new ... is an expression (anonymous type or not) and the result of that expression (a new object) is passed as an argument to fubar. The formatting is mostly arbitrary -- it could have been all on one line. Consider this code:

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

Hope that clears things up.

Upvotes: 3

QuantumMechanic
QuantumMechanic

Reputation: 13946

It's called an anonymous inner class. You are creating an implementation of Foo on the fly instead of having to write a named class.

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

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 992767

This is called an anonymous inner class. A new class, with a compiler-generated name, is created at the point you do new Foo() { ... }. This new class implements the Foo interface. It's roughly equivalent to:

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()
        );
    }
}

(I have assumed that the missing space between new and Foo in your example is an error.)

Upvotes: 3

Related Questions