组合 内部类的联系
面向过程
public class Count {
public static void main(String[] args) {
// TODO 自动生成的方法存
new Count_();
}
}
class Count_ extends Frame {
public Count_(){
TextField f1=new TextField(10);
TextField f2=new TextField(10);
TextField f3=new TextField(20);
Button button=new Button("=");
button.addActionListener(new MyCountLinstener(f1, f2, f3));
Label label=new Label("+");
setLayout(new FlowLayout());
add(f1);
add(label);
add(f2);
add(button);
add(f3);
setSize(200,200);
pack();
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyCountLinstener implements ActionListener{
private TextField n1, n2, n3;
public MyCountLinstener(TextField f1,TextField f2,TextField f3){
n1=f1;n2=f2;n3=f3;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
int x=Integer.parseInt(n1.getText());
int y=Integer.parseInt(n2.getText());
n3.setText(" "+(x+y));
n1.setText(" ");
n2.setText(" ");
}
}
改造成面向对象
public class Count {
public static void main(String[] args) {
// TODO 自动生成的方法存根
new Count_().LoadCount_();//调用加法计算类中的方法 实现窗口
}
}
//加法计算类
class Count_ extends Frame {
TextField f1,f2,f3;//属性
public void LoadCount_(){//方法
f1=new TextField(10);
f2=new TextField(10);
f3=new TextField(20);
Button button=new Button("=");
button.addActionListener(new MyCountLinstener(this));
Label label=new Label("+");
setLayout(new FlowLayout());
add(f1);
add(label);
add(f2);
add(button);
add(f3);
setSize(200,200);
pack();
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
class MyCountLinstener implements ActionListener{
//在一个类中组合另一个类
Count_ count_=null;
public MyCountLinstener(Count_ count_){
this.count_=count_;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
int x=Integer.parseInt(count_.f1.getText());
int y=Integer.parseInt(count_.f2.getText());
count_.f3.setText(" "+(x+y));
count_.f1.setText(" ");
count_.f2.setText(" ");
}
}
内部类
public class Count {
public static void main(String[] args) {
// TODO 自动生成的方法存根
new Count_().LoadCount_();//调用加法计算类中的方法 实现窗口
}
}
//加法计算类
class Count_ extends Frame {
TextField f1,f2,f3;//属性
public void LoadCount_(){//方法
f1=new TextField(10);
f2=new TextField(10);
f3=new TextField(20);
Button button=new Button("=");
button.addActionListener(new MyCountLinstener());
Label label=new Label("+");
setLayout(new FlowLayout());
add(f1);
add(label);
add(f2);
add(button);
add(f3);
setSize(200,200);
pack();
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private class MyCountLinstener implements ActionListener{
//在一个类中组合另一个类
@Override
public void actionPerformed(ActionEvent e) {
// TODO 自动生成的方法存根
int x=Integer.parseInt(f1.getText());
int y=Integer.parseInt(f2.getText());
f3.setText(" "+(x+y));
f1.setText(" ");
f2.setText(" ");
}
}
}
内部类可以减少代码,随意访问外部属性和方法