1

When events are registered in the init() method of the Applet, we add the method addTypeListener(this).

But I know that the keyword this refers to the object that called the method. So, when we haven't created any object of the applet class what would the this refer to? please clarify my doubts.

Tiny
  • 27,221
  • 105
  • 339
  • 599

3 Answers3

2

The reason why this works when you haven't explicitly created an instance of your Applet is because the JRE treats Applets a little differently.

Applets are a special class that Java instantiates for you upon loading. From there, the object is owned by the JRE and is interfaced with by such.

Once Java creates an instance of your applet, it then calls init() in lieu of a constructor (since constructors cannot conform to a prototypical contract).

Likewise, when your applet is done or the page is unloaded, Java worries about shutting down your applet.

Community
  • 1
  • 1
Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
1

But I know that the keyword this refers to the object that called the method.

That's not quite true. Actually in an instance method's code,
this refers to the object the method was called on.

So, when we haven't created any object of the applet class what would the this refer to?

The JVM has created an object/instance of your Applet class (subclass that is),
so this refers to that instance of your Applet class.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159
-1

'this' keyword refers to the object of the class on which you are working. 'This' keyword can be used to call the default constructor of the class. Similarly while using inheritance concept, 'super' keyword is use to call the default constructor of the inherited class or can be referred as the inherited /parent class' object.

Himanshu
  • 23
  • 6
  • `super()` and `this` have nothing to do with default constructors in particular. – Jeroen Vannevel Oct 08 '14 at 16:47
  • 1
    `'This' keyword can be used to call the default constructor of the class.` Wrong; `this` can be used in a constructor to call *any other* constructor. Likewise, `super` can be used to call any constructor of the direct parent class. Like `this`, `super` can be used in methods as well, to call parent versions of the method. – Qix - MONICA WAS MISTREATED Oct 08 '14 at 16:53