0

This might well be a very noob question but I am one so it would be great if you could explain in an easy to understand manner for me.

so I was following up with a swing tutorial and faced this

nameOfButton.addActionListener(this);

so I know what this is when used in context of constructor as it calls itself again.

Also I know what it does in terms of relating parameters of method to variables within the class.

But I am curious to what this in such instance refers to. Does it refer to the button itself? so does it mean it's creating an action listener of itself or does it somehow refer to the method it is in? Thank you

forJ
  • 4,309
  • 6
  • 34
  • 60
  • `this` refers to the current class, which (assume the code compiles) implements `ActionListener`. Have a look at [Using the this Keyword](https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html) for more details – MadProgrammer Feb 18 '16 at 02:26
  • This [answer](http://stackoverflow.com/a/6520977/4924793) and [this one](http://stackoverflow.com/a/3572553/4924793) might be of help to you. – Emzor Feb 18 '16 at 02:31

2 Answers2

2

The method addActionListener is part of a Listener class, i guess. If you use this method and it is not static, it means that a listener object of that class was instantiated and has accessed the method. The reference "this" is to that object. It is being assigned with a button inside the class It resides in.

This is a simplified example from a code I wrote for some project:

public class Foo {

private Company company;

public Foo login(String name) {
    name = name.toLowerCase();
    company = companyDAO.getCompanyByName(name);
    return this;
}

As you can see, my class Foo has an attribute and when a Foo object in main() calls the method login: Foo f = new Foo().login("someName"), It will receive itself but its attribute - "company" - will have a unique value. You could write It in another way, but this way is easier.

MaxG
  • 1,079
  • 2
  • 13
  • 26
  • Thank you for that but why do you have to pass a parameter of object of itself when performing addActionListener ? – forJ Feb 18 '16 at 12:04
  • 1
    I've added an example of code that uses `this` in the same way. I don't know what is the logic of the code you added so I can't tell. – MaxG Feb 18 '16 at 12:39
0

That statement is in a method of a class. Let's call the class Foo. this references the Foo instance used to call the method.

cybersam
  • 63,203
  • 6
  • 53
  • 76