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?
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With