Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java interface problem

Tags:

java

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?

like image 913
mriganka3 Avatar asked Dec 28 '25 16:12

mriganka3


1 Answers

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.)

like image 51
Greg Hewgill Avatar answered Dec 30 '25 05:12

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!