Techie Person
Techie Person

Reputation: 21

Understanding this keyword in Java

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.

Upvotes: 1

Views: 460

Answers (3)

peter.petrov
peter.petrov

Reputation: 39477

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.

Upvotes: 1

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.

Upvotes: 2

Himanshu
Himanshu

Reputation: 23

'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.

Upvotes: -1

Related Questions