java内部类使用场景体会

内部类的作用:

1.完善多重继承。
[u]疑问在于:[/u]多重继承可以用组合的方式实现。内部类相对组合方式的优势应该就是内聚更好,因为内部类实现的逻辑对除了自己外部类以外的类是不透明的,代码专用。
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); //这里用到了外部类的私有成员变量
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值