组合大于继承
class A extends B{
}
class A {
public B b;
}
计算器初级代码
class myCalculator extends Frame{
public myCalculator(){
TextField num1 = new TextField("10");
TextField num2 = new TextField("10");
TextField resl = new TextField("20");
Button but1 = new Button("=");
Label l1 = new Label("+");
setLayout(new FlowLayout());
add(num1);
add(l1);
add(num2);
add(but1);
add(resl);
pack();
setVisible(true);
but1.addActionListener(new myCalculatorListener(num1,num2,resl));
}
}
class myCalculatorListener implements ActionListener{
private TextField num1;
private TextField num2;
private TextField res;
public myCalculatorListener(TextField num1 ,TextField num2,TextField res) {
this.num1= num1;
this.num2= num2;
this.res=res;
}
@Override
public void actionPerformed(ActionEvent e) {
int n1 =Integer.parseInt(num1.getText());
int n2 =Integer.parseInt(num2.getText());
res.setText(""+(n1+n2));
num1.setText("");
num2.setText("");
}
}
计算器修改代码(更加面型对象)
public class gui {
public static void main(String[] args) {
new myCalculator().loadFrame();
}
}
class myCalculator extends Frame{
TextField num1,num2,resl;
public void loadFrame(){
num1 = new TextField("10");
num2 = new TextField("10");
resl = new TextField("20");
Button but1 = new Button("=");
Label l1 = new Label("+");
but1.addActionListener(new myCalculatorListener(this));
setLayout(new FlowLayout());
add(num1);
add(l1);
add(num2);
add(but1);
add(resl);
pack();
setVisible(true);
}
}
class myCalculatorListener implements ActionListener{
myCalculator cal = null;
public myCalculatorListener(myCalculator calculator){
this.cal = calculator;
}
@Override
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(cal.num1.getText());
int n2 = Integer.parseInt(cal.num2.getText());
cal.resl.setText(""+(n1+n2));
cal.num1.setText("");
cal.num2.setText("");
}
}
完全改造为面向对象(内部类)
public class gui {
public static void main(String[] args) {
new myCalculator().loadFrame();
}
}
class myCalculator extends Frame{
TextField num1,num2,resl;
public void loadFrame(){
num1 = new TextField("10");
num2 = new TextField("10");
resl = new TextField("20");
Button but1 = new Button("=");
Label l1 = new Label("+");
but1.addActionListener(new myCalculatorListener());
setLayout(new FlowLayout());
add(num1);
add(l1);
add(num2);
add(but1);
add(resl);
pack();
setVisible(true);
}
private class myCalculatorListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
resl.setText(""+(n1+n2));
num1.setText("");
num2.setText("");
}
}
}