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?
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With