this question is from K&B Self Tests.... i could not understand the solution..any help is appreciated
1. class Test { 2. public static Foo f = new Foo(); 3. public static Foo f2; 4. public static Bar b = new Bar(); 5. 6. public static void main(String [] args) { 7. for (int x=0; x<6; x++) { 8. f2 = getFoo(x); 9. f2.react(); 10. } 11. } 12. static Foo getFoo(int y) { 13. if ( 0 == y % 2 ) { 14. return f; 15. } else { 16. return b; 17. } 18. } 19. } 20. 21. class Bar extends Foo { 22. void react() { System.out.print("Bar "); } 23. } 24. 25. class Foo { 26. void react() { System.out.print("Foo "); } 27. } what is the result?
ans is Foo Bar Foo Bar Foo Bar my guess is that it should be Bar Bar Foo Bar Foo Bar as overridden methods are called based on runtime type of the object ....
vandu matcha
Ranch Hand
Joined: Dec 28, 2005
Posts: 57
posted
0
got it ....when i executed the program..Y%2 is giving 0..so if condition is true...hence the output is Foo Bar Foo Bar Foo Bar....
Michael Carlson
Ranch Hand
Joined: Sep 11, 2005
Posts: 78
posted
0
I think the problem your having is with the expression: (0 == y % 2) for example if((0 == 0 % 2)) is true.
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
posted
0
I read "if (0 == y%2)" to mean "if y is even". This is a very common idiom. Since 0 is even, then this expression will evaluate to true.
yes exactly ...i was confused ..i thought 0%2 is 2....but later i recognised that arithmetic operation of / and % with 0 as divident is always 0.....thanks for the responses...