The "this" keyword

+1 Black Boy · November 4, 2015

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.methods(); -> not sure if acceptable 

or by repeating constructor:

public class example{

public example(int ex){


public example(int ex,int ex2){




but when it comes for references like this one:


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


//and then

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


 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:

Thanks for helping!

Post a Reply


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:
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:


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


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


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

Bucky Roberts Administrator