Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" in JAVA, more explanation

Tags:

java

this

Suppose that I have a code like this

public void init(){
    addMouseListener(this);
    addMouseMotionListener(this);
}

Based on JAVA docs,

Within a method or constructor, this refers to the current object, the object whose method or constructor is being called ...

based on the code, I can take a conclusion that "this" refers to the object on which init() method is called not addMouseListener() or addMouseMotionListener()

is it true?

like image 474
Edi Avatar asked Nov 30 '25 05:11

Edi


2 Answers

this refers to the current object, the one that has the init method, yes, and the one that you're adding your MouseListener and MouseMotionListener to. It also is the MouseListener and MouseMotionListener. You may be asking this poor class to do too much.

I suggest that you don't have your GUI or applet classes also implement listener interfaces since this can make your code difficult to debug and extend.

like image 73
Hovercraft Full Of Eels Avatar answered Dec 02 '25 17:12

Hovercraft Full Of Eels


Not exactly. When you do

someFunction();

it's the same as doing

this.someFunction();

So in your example, you have some Object that both TAKES listeners and IS a listener. Essentially you're telling the Object to listen to itself. You're doing

this.addMouseListener(this);

The initial this is implied when the method isn't qualified.

The same goes for static methods too. If you have a static void someStatic() { }, any time you call someStatic(); it's the same as going MyClass.someStatic();

like image 45
corsiKa Avatar answered Dec 02 '25 19:12

corsiKa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!