Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

about "this"  RSS feed

 
Tim Leung
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.awt.*;
import java.awt.event.*;

/**
* Sample application using Frame.
*
* @author
* @version 1.00 04/09/05
*/
public class Test2Frame extends Frame {

/**
* The constructor.
*/
public Test2Frame() {

MenuBar menuBar = new MenuBar();
Menu menuFile = new Menu();
MenuItem menuFileExit = new MenuItem();

menuFile.setLabel("File");
menuFileExit.setLabel("Exit");

// Add action listener.for the menu button




// method 2: using annoyamous inner class

menuFileExit.addActionListener
(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
Test2Frame.this.windowClosed();
}
}
);

// method 2 end.
menuFile.add(menuFileExit);
menuBar.add(menuFile);

setTitle("Test2");
setMenuBar(menuBar);
setSize(new Dimension(400, 400));

// Add window listener.

class ClsMM extends WindowAdapter{
public void windowClosing(WindowEvent e) {
Test2Frame.this.windowClosed() -> Q1

}
}
ClsMM clsMM=new ClsMM();
this.addWindowListener(clsMM);

}


/**
* Shutdown procedure when run as an application.
*/
protected void windowClosed() {

// TODO: Check if it is safe to close the application

// Exit application.
System.exit(0);
}
}

Based on line Q1, what does "this" stands for which class? Test2Frame or ClsMM? Why?
 
Richard Bradford
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'this' refers to the current object. ie the object that the 'this' appears in. The current object will be an instance of Test2Frame.
 
Tim Leung
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know it now.
You mentions that if I created an object called "abc" in this case, then "this" refer to "abc" when "abc" instance of "Test2Frame". It that right?
 
Julian Kennedy
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tim,

I think you've got it. Consider this slightly simplified example:

When used in a method of MyClass, "this" refers to an instance of MyClass. MyMemberClass in an inner class. When used in a method of MyMemberClass, "this" refers to an instance of MyMemberClass. If you want to refer to the instance of MyClass from within a method of MyMemberClass you need to use "MyClass.this", i.e. you prefix "this" with the classname of the type of instance you want to refer to.

I hope that helps.

Jules
 
Tim Leung
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much. I know it.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!