/* * File: SemanticError.java * Author: Java, Java, Java * Description: This applet illustrates a common semantic * error, that of redeclaring a global variabe within a method. * Note that a Button b1 is declared at the class * level, but never instantiated. Another Button b1 is * declared within the init() method, and this one is * instantiated and is given an ActionListener. However, because this * one has local scope it cannot be referred to outside of the init() * method. So in actionPerfored(), b1 refers to the global button, * which was not instantiated. This causes a NullPointerException to * be thrown. * To fix this problem, don't redeclare b1 in the init() method. * Just instantiate it there: * b1 = new Button("Local"); */ import java.awt.*; import java.applet.*; import java.awt.event.*; public class SemanticError extends Applet implements ActionListener { private Button b1; // This b1 has class scope but is not instantiated public void init() { // Declare and instantiate a local b1 Button b1 = new Button ("Local"); // This b1 has local scope add(b1); // The local b1 is added to the applet b1.addActionListener(this); } // init() public void actionPerformed(ActionEvent e) { b1.setLabel("Global"); // This refers to the uninstantiated b1. } // actionPerformed() } // SemanticError