PDA

View Full Version : Truyên tham số



Don
30-03-2003, 20:57
Tôi có đọc sách, ngườI ta nói trong Java, khi truyền tham số cho một hàm thi không có truyền tham biến.
Nhưng trong sách: Giáo trinh Lý thuyế va bài tập Java cua TRẦN TIẾN DŨNG co vi dụ (6-9), như sau:


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

public class BGSetter extends Object implements ActionListener{
Component component;
Color color;

public BGSetter(Component component, Color color){
this.component = component;
this.color = color;
}
public void actionPerformed(ActionEvent evt) {
component.setBackground(color);
component.repaint();
}
}

import java.awt.*;

public class Button2Applet extends Applet
{
public void init()
{
Button red = new Button("Red");
add(red);
red.addActionListener(new BGSetter(this, Color.red));

Button blue = new Button("Blue");
add(blue);
blue.addActionListener(new BGSetter(this, Color.blue));
}
}

Theo tôi nghi thì trong vi du trên khi truyên tham số “this” cho đốI tượng new BGSetter(this, Color.red)); chính là truyền tham biến.
Các bạn có thể giai thích giúp tôi trường hợp này không!

abcdef
30-03-2003, 22:48
Theo tui thì ngược lại, truyền tham số trong Java luôn là truyền tham biến bởi vì trong Java "mọi thứ đều là đối tượng". Trừ đối với các primitive variables luôn truyền theo tham trị, nếu muốn truyền tham biến bạn phải chuyển chúng về các lớp "bọc", ví dụ int -> Interger, ....