The "this" keyword

+1 Black Boy · November 4, 2015
Hi,

l'm still having trouble with 'this' keyword.

I know that you can use it to prioritize variable first and methods by doing the following:

this.variable;


this.methods(); -> not sure if acceptable 

or by repeating constructor:

public class example{


public example(int ex){


this(0,ex)


}
public example(int ex,int ex2){

this(ex2,ex)

}



}


but when it comes for references like this one:

example.addActionListener(this);

I tend to be lost but at least I discover that in handling event it's the same as this: 

Item1.addActionListener(this);


//and then

Public void ActionPerformed(ActionEvent event){
// code here
}


 SAME AS 

 
 Item1.addItemListener(new ActionListener(){
public void ActionPerformed(ActionEvent event){
//code here
}});

I'm still new to this but anyone who can give me some advice on that  should be great help to me.

and I also need some help on this post:

https://www.thenewboston.com/forum/topic.php?id=10045


Thanks for helping!


Post a Reply

Replies

Oldest  Newest  Rating
0 Gary Whitney · December 18, 2015
Generally speaking this refers to the object that contains it. It is a shortcut that keeps you from having to type the fully qualified name of the object you are using.

You can use it to represent the context or environment of a Activity when the method you are calling requires a context parameter.

As for:
example.addActionListener(this);
Here this is used to register the ActionListener with the example that generates the event.
0 Black Boy · December 19, 2015
So in short it autogenerate the method event for you because it is the same class  as ActionPerformed?
0 Nicholas Eason · December 25, 2015
When you say:

button.addActionListener(this);


You're just assigning it to the same event listener as anything else that uses the this keyword 

versus

button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Do whatever here
}
});

What this does is create a new instance of an ActionListener.
The main difference between the two is reuseability. If you declare it in the second way, you only have access for 1 object to use that listener, which isn't good when you need, say, 5 things to access that listener.
When you need multiple things to access the same listener, then you should use the this way, simply because it saves memory.
  • 1

Java / Android Development

107,205 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator