如果一个类是本地内部类,这是否意味着它位于另一个类的方法内部,或者是否意味着它只是在某个地方的另一个方法中定义。
例如,在下面的代码中,MenuListener 是否被视为内部本地类?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuDemo extends JFrame{
private Container c;
private ImageIcon[] images = new ImageIcon[5];
private JLabel picture;
private JPanel mainPanel;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem bird,cat,dog,rabbit,pig;
public MenuDemo() {
super("Menu Demo");
c = getContentPane();
c.setLayout(new BorderLayout());
mainPanel = new JPanel();
// Store the animal pictures in an array.
for (int i=0; i<5; i++){
images[i] = new ImageIcon("image" + i + ".gif");
}
//Set up the picture label.
picture = new JLabel(images[0]);
picture.setPreferredSize(new Dimension(177,122));
mainPanel.add(picture, BorderLayout.CENTER);
c.add(mainPanel);
buildMenuBar();
this.setJMenuBar(menuBar);
pack();
setVisible(true);
}
private void buildMenuBar(){
MenuListener listener = new MenuListener();
menuBar = new JMenuBar();
menu = new JMenu("Animals");
menu.setMnemonic(KeyEvent.VK_A);
menuBar.add(menu);
bird = new JMenuItem("Bird", KeyEvent.VK_B);
bird.addActionListener(listener);
menu.add(bird);
cat = new JMenuItem("Cat", KeyEvent.VK_C);
cat.addActionListener(listener);
menu.add(cat);
dog = new JMenuItem("Dog", KeyEvent.VK_D);
dog.addActionListener(listener);
menu.add(dog);
rabbit = new JMenuItem("Rabbit", KeyEvent.VK_R);
rabbit.addActionListener(listener);
menu.add(rabbit);
pig = new JMenuItem("Pig", KeyEvent.VK_P);
pig.addActionListener(listener);
menu.add(pig);
}
private class MenuListener implements ActionListener {
public void actionPerformed(ActionEvent e){
if (e.getSource() == bird)
picture.setIcon(images[0]);
else if (e.getSource() == cat)
picture.setIcon(images[1]);
else if (e.getSource() == dog)
picture.setIcon(images[2]);
else if (e.getSource() == rabbit)
picture.setIcon(images[3]);
if (e.getSource() == pig)
picture.setIcon(images[4]);
}
}
public static void main(String[] args){
MenuDemo m = new MenuDemo();
m.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
根据一些官方的Oracle Java教程 http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html,局部内部类是在代码块中定义的类,而不是另一个类定义的一部分。这意味着在方法内部或初始化块中定义的类。
遵循该定义,MenuListener
不是本地内部类——它只是一个内部类。
So:
public class Outer {
public class Inner1 {
}
public static class Inner2 {
}
public void method(){
class LocalInner{
}
LocalInner yesThisActuallyCompiles = new LocalInner();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)