码迷,mamicode.com
首页 > 其他好文 > 详细

内部类

时间:2015-01-31 16:27:04      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:内部类

内部类可以直接访问包装类的成员变量,好处有两个:

1):可以方便的访问包装类的成员

2):可以更清楚的组织逻辑,防止不应该被其他类访问的累进行访问。

那么何时使用呢?

该类不允许或不需要其它类进行访问时。

import java.awt.*;
import java.awt.event.*;

public class TFMath {
	public static void main(String[] args) {
		new TFFrame().launchFrame();
	}	
}

class TFFrame extends Frame {
	TextField num1,num2,num3;
	public void launchFrame()  {
		num1 = new TextField(10);	
		num2 = new TextField(10);	
		num3 = new TextField(15);
		Label l = new Label("+");
		Button b = new Button("=");
		b.addActionListener(new MyMonitor());
		setLayout(new FlowLayout());	
		add(num1);
		add(l);
		add(num2);
		add(b);
		add(num3);
		pack();
		setVisible(true);
		
		
	}
	
	private class MyMonitor implements ActionListener {
		public void actionPerformed(ActionEvent e)  {

		int n1 = Integer.parseInt(num1.getText());
		int n2 = Integer.parseInt(num2.getText());
		num3.setText("" +(n1 + n2));
		}
	}
}
将MyMonitor作为TFFrame的内部类,那么就可以无条件的使用TTFrame的成员变量和局部变量了。这样就更加方便。这是对上一篇的改进。

内部类

标签:内部类

原文地址:http://blog.csdn.net/erpng/article/details/43340275

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!