如果一個類是一個本地內部類,這是否意味着它在另一個類的方法內,或者是否意味着它只是在另一個方法中定義的。java中的內部類和本地內部類有什麼區別?
例如,在下面的代碼中,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);
}
}
我只有這樣一個事實,即人們可以實際聲明類本地方法絆了一年或兩年前,到目前爲止有沒有找到任何實際用途:(嗯,它可能是最好的 – Voo
+1'yesThisActuallyCompiles'。我不知道這是否剛剛存在。我花了幾個通行證才真正看到這個類是包裹在一個方法聲明中,謝謝你糾正我的錯誤 –
它不能被標記爲最終的抽象和公共的,但它可以是靜態的? – Charlie