`
xly1981
  • 浏览: 142449 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

java内部类使用场景体会

    博客分类:
  • java
 
阅读更多
内部类的作用:

1.完善多重继承。
疑问在于:多重继承可以用组合的方式实现。内部类相对组合方式的优势应该就是内聚更好,因为内部类实现的逻辑对除了自己外部类以外的类是不透明的,代码专用。
Lock相关实现类里面的 Sync这个内部类均扩展了抽象类AQS,并实现AQS的tryAcquire、tryRelease、tryAcquireShared等方法,各个Lock类的Sync各是各的,而且自己用自己的。



2.实现事件驱动系统
用在回调的场景里面,感觉也是代码专用的效果,这是外部对内部的;另外有些场景外部类的私有变量内部类才能访问,那就既是约束,也是方便了。

1.addActionListener方法调用接口ActionListener的实现类--事件驱动模型系统
2.ActionListener接口的实现类又要使用别人ContentPane这个私有成员变量

addActionListener 方法要调用一个能访问自己私有成员变量的类,那只能是一个内部类了

public class ButtonTest extends JFrame {
    private static final long serialVersionUID = -5726190585100402900L;
    private JPanel contentPane;

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ButtonTest frame = new ButtonTest();
                    frame.setVisible(true);
                    frame.contentPane.requestFocus();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**
     * Create the frame.
     */

    public ButtonTest() {
        setTitle("普通内部类的简单应用");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 300, 200);
        contentPane = new JPanel();
        contentPane.setLayout(null);
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        final JButton redButton = new JButton();
        redButton.setText("红色");
        redButton.setBounds(15, 20, 82, 30);
        redButton.addActionListener(new ColorAction(Color.RED));//这里用事件模型
        contentPane.add(redButton);
    }
    
    private class ColorAction implements ActionListener {
        private Color background;        
        public ColorAction(Color background) {
            this.background = background;
        }

        public void actionPerformed(ActionEvent e) {
            contentPane.setBackground(background); //这里用到了外部类的私有成员变量
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics