this.?
could someone tell me when should i put 'this.' in front of methods that are in the same class? sould i do this all the time out of good pratice or only sumtimes.if so, when?thanks
could someone tell me when should i put 'this.' in front of methods that are in the same class? sould i do this all the time out of good pratice or only sumtimes.if so, when?thanks
When it comes to methods, you never need this. I consider it bad practice because it's redundant.
When you this. in front of a member is for variables that have the same name as local variables.
Using this. when not required is somewhat a matter of style, but I prefer to not use it when not required. I consider it redundant and cluttersome.
As jverd said, I like to use this. for clarity (local variables matching instance variables, etc). I also use it when developing Swing applications ... again for clarity as it "marks off" the parts of my code where I'm actually manipulating the component itself. (As an example of both of those situations):
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
class ListItem {
private String text;
private Object value;
public ListItem() { }
public ListItem(String text, Object value) {
this.text = text;
this.value = value;
}
public void setText(String text) {
this.text = text;
}
public void setValue(Object value) {
this.value = value;
}
public String getText() {
return text;
}
public Object getValue() {
return value;
}
public String toString() {
return getText();
}
}
public class Test extends JFrame {
private JScrollPane jsp;
private JList list;
public Test() {
initComponents();
}
private void initComponents() {
ListItem[] items = new ListItem[3];
items[0] = new ListItem("Navy_Coder", "Awesome Guy");
items[1] = new ListItem("jverd", "Pretty Cool");
items[2] = new ListItem("duffymo", "... Pretty Old!");
list = new JList(items);
jsp = new JScrollPane(list);
this.getContentPane().add(jsp);
this.pack();
this.setSize(300, 500);
this.setTitle("Demo");
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if( evt.getButton() == MouseEvent.BUTTON1 ) {
ListItem item = (ListItem)list.getSelectedValue();
System.out.println(item.getText());
System.out.println(item.getValue());
}
}
});
}
public static void main(String[] argv) {
new Test().setVisible(true);
}
}