HI import java.awt.*; import java.awt.event.*; public class fram extends Frame { public static void main(String arg[]) { fram f = new fram(); String msg = "hello"; Button b = new Button("Click"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println(msg); } }); f.add(b); f.pack(); f.show(); } }
Which of the following statements is true about the above code?
A.
The code will not compile complaining that no layout has been defined for the frame. B.
The code compiles and doesn't display anything. C.
The code runs and shows a single button occupying the whole frame. On clicking the button you get the message "hello" at the Std o/p. D.
The code does not compile complaining about the inaccessibility of a certain variable. E.
The code doesn't compile complaining that the constructor for fram has not been defined. THE ANSWER GIVEN IS CAN ANYBOD PLEASE EXPLAIN THANKS SHERI
Sagar Sharma
Ranch Hand
Joined: Aug 31, 2000
Posts: 92
posted
0
since msg is a non-final variable you cannot access it from an anonymous class so d is the answer
Stephanie Grasson
Ranch Hand
Joined: Jun 14, 2000
Posts: 347
posted
0
Sheri, The correct answer is (D). (The code does not compile complaining about the inaccessibility of a certain variable). The actual error message is: "Attempt to use a non-final variable msg from a different method. From enclosing blocks, only final local variables are available." You can test it for yourself. The error message is very clear. In the place that msg is used, only final local variables are available. If you were to change the declaration of msg to be: final String msg = "hello"; the code would compile. About the other answers: (A) is wrong because if no layout manager is set, Frame will use its default layout manager, which is Border layout manager. (B) is wrong because the code obviously does not compile. (C) is wrong because, if the code won't even compile, it obviously cannot run. (E) is wrong because, if a constructor is not explicitly declared, a default constructor will be assigned. Hope this helps. Stephanie