When to use "this." when not to ?

Hi, I know this will be a basic question, but can someone tell me the rule of when to use this.method/variable/etc and when not to ?
If I have (And I'll cut down the code,leaving construtors, etc.)
public abstract class DataStuff
protected String message = null;
protected void clearMessage()
this.message = null; // Do I use this.
message = null; // Or not ?
} // End clearMessage()
} // End Class ---------
Lets get more complicated
public class MoreStuff extends DataStuff
public void someMethod()
this.message = "Do I use This ?";
message = "Or Do I not ?";
this.clearMessage(); // or
clearMessage();
} // End someMethod()
} // End Class ------
I know this will be fairly simple, and I am sure there are lots of Tutorials I could not find that explain the difference between "this"
thanks
Paul

Besides using the this reference for instance variables that have the same name as a local variable, it is also used when your class implements an interface and uses it in the class. Let me further explain. Lets pretend that you create a JFrame that has buttons on it. You want your buttons to handle events so you add an ActionListener to the buttons. You also want to code your event handling in the JFrame so you cause your JFrame to implement the ActionListener interface and implement the required method actionPerformed() in your JFrame class. Well, when you add and actionListener to the buttons, you have to use the this reference in the method signature. See code for example.import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class ExampleJFrame extends JFrame implements ActionListener {
   public ExampleJFrame() {
      super("Example using 'this' reference!");
      Container c = getContentPane();
      JButton button = new JButton("Push Me");
      /* Here is the example of how the 'this' reference is
         used.  Since this class implements ActionListener,
         that means it is an ActionListener.  So, when
         we add the method addActionListener to the button,
         it requires that an ActionListener be put into
         the method signature.  So, I just pass a reference
         to this class into it (using the 'this' reference).
         Its actionPerformed method will be called.  There
         are 3 ways I could think of to handle the
         events for this button.  One is to do it the way
         I chose to do it; that is, have the originating
         class (ExampleJFrame) handle it.  That is where
         the 'this' reference comes into play.  Two is
         to use an anonymous inner class.  The second
         option is useful if the code is small and
         self contained.  Three is to have another
         class handle it, such as an Action. */
      button.addActionListener(this);
      c.add(button);
      /* incidentally, you could put the this keyword in
         front of each of these methods for readability,
         but most people don't. I used it on the first
         one to demonstrate it.  */
               //cause the program to end when closing
      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      pack();
      setVisible(true);
   }//end constructor
   /*=**************************************************
   * actionPerformed(): required ActionListener method *
   public void actionPerformed(ActionEvent e) {
      /* the this reference is also used in here because
         the showMessageDialog() should have as its
         parent a component and we want the component to
         be this JFrame */
      JOptionPane.showMessageDialog(this,"You used the this pointer!");
   }//end actionPerformed
   public static void main(String args[]) {
      /* when you run this class, a small JFrame with
         a button will appear in the top left corner. */
      ExampleJFrame app = new ExampleJFrame();
   }//end main
}//end ExampleJFrame classtajenkins

Similar Messages

  • I keep getting offers to clean my imac, Mackeeper its called is it a good idea to use this or not?

    Ikeep getting offers to clean my imac, the offer is from mackeeper,  one should a person clean the mac, and if so is this the product to use or not.

    If it were that good, every-other post here would be recommending it. (None do.)
    Instead, it is like online SPAM -- in your face, trying to sell you garbage.
    Everything you have to have to keep your Mac working right is already installed at the factory. In certain unusual situations, you may need another program or two. Nothing is needed to clean your Mac -- it does not get filthy.

  • Use this or not

    does using the "this" keyword for calling private methods or variables have overhead?
    is it recommended?

    does using the "this" keyword for calling private methods or variables have overhead?No.
    is it recommended?I only use it where necessary to disambiguate, typically in a constructor:
    public class Name {
      private String name;
      public Name(String name) {
        this.name = name;
    }

  • My account is asking for 2 security question answers. I have never had to do this before. Saying it is the first time I have used this computer to purchase not true I have used this computer everythime. Then it tells me that I put in the wrong answers.

    My account keeps asking for 2 security question answers saying this is the first time I used this computer not true used this computer many times. Then when I put ansers in says incorrect answers. What's up with this?

    There have a few other posts from people saying that they are being asked their questions despite it not being the first purchase on the computer or device.
    If you have a rescue email address (which is not the same thing as an alternate email address) set up on your account then go to https://appleid.apple.com/ and click 'Manage your Apple ID' on the right-hand side of that page and log into your account. Then click on 'Password and Security' on the left-hand side of that page and on the right-hand side you should see an option to send security question reset info to your rescue email address.
    If you don't have a rescue email address (you won't be able to add one until you can answer 2 of your questions) then you won't get the reset option - you will need to contact iTunes Support or Apple to get them reset.
    e.g. you can try contacting iTunes Support :http://www.apple.com/support/itunes/contact/ - click on Contact iTunes Store Support on the right-hand side of the page, then Account Management , and then 'Forgotten Apple ID security questions'
    or try ringing Apple in your country and ask to talk to the Accounts Security Team :http://support.apple.com/kb/HE57
    When they've been reset (and if you don't already have a rescue email address) you can then use the steps half-way down this page to add a rescue email address for potential future use : http://support.apple.com/kb/HT5312 . Or you could change to 2-step verification : http://support.apple.com/kb/HT5570

  • Can I use this in EJB

    I am using log4j in my project. like
    Logger.error(this, "Error occured");
    I am told that in EJB using 'this' is not advisable. Is it so? why?

    I am confused.
    I am not getting any error while using 'this'.
    In my server console I am getting proper log message
    if I use
    Logger.info(this, ".......");Yes, you can use "this".
    Also I want to know can I use
    this.getClass(),getName() to get the full qualified
    name of the EJB ?Yes, of course. You will get class name of EJB bean. It's not the same as EJB name what you specify in deployment descriptor.

  • Example problem using 'this'

    Tried working out an exercise question from a tutorial book im reading and one of the questions was :
    Create a class with two methods. Within the first method,
    call the second method twice: the first time without using this, and the
    second time using this—just to see it working
    Read through alot of how to use this but not entirely sure how id call a method using this from the same method
    as i called it regularly from .

    Sample code that would do same is :-
    class Try1{
    public void a()
              System.out.println("In A");
              b();
              this.b();
         public void b(){
              System.out.println("In B ");
         public static void main(String [] args){
              Try1 t = new Try1();
              t.a();
    Output :-
    java Try1In A
    In B
    In B

  • I can't open my gmail or send gmails on Firefox. I can read and send gmails on other servers. It started when I was using a hotels wireless connection. Firefox said that this was not a secure site and asked if I wanted to overide it. Since then I have

    I cannot open my gmail nor send any gmails on Firefox. My wife also has gmail and she has no problem on firefox opening or sending her gmails. Also, I cannot access my settings. It started when I was at a hotel last Friday using their wireless connection. When I turned firefox on, which automatically goes to gmail, firefox would not open my gmail as it stated that this was not a secure site. I probable did something incorrectly and I got blocked out. All my other bookmarks work fine. I can access my gmail using other servers. Please help. Thank you.
    == This happened ==
    Every time Firefox opened
    == June 11

    how can i open my gmail at mozilla firefox? because i cant open it..

  • I have a targus 4.0 bluetooth usb adapter and so i can pair my iphone 4s and ipad air wirelessly, it seems to pair ok but when i try to connect i get a error message or not compatible. can some one tell me if it i can use this

    i have a targus 4.0 bluetooth usb adapter and so i can pair my iphone 4s and ipad air wirelessly, it seems to pair ok but when i try to connect i get a error message or not compatible. can some one tell me if it i can use this bluetooth with my devices, thanks

    sos1der wrote:
    pairing the apple equipment is not a big deal just wanted to add songs from itunes wirelessly.
    You can only add songs to your iOS device from iTunes via Wi-Fi sync or via your cable, not Bluetooth.
    sos1der wrote:
    but i tried paring my LG bluetooth so i can listen to music on my computer wirelessly buy it gives me the same error message
    That's an entirely different issue, unrelated to your iOS devices.

  • WHEN I USED TO CONNECT INTERNET FROM MY IPHONE 4S PERSONAL HOTSPOT VIA USB, AN ICON IN THE NETWORK PREFERENCE NAMED "IPHONE" GETS OPENED.... BUT NOW THIS IS NOT HAPPENING AND I AM NOT ABLE TO CONNECCT PERSONAL HOTSPOT VIA USB CABLE. PLEASE HELP ME OUT

    WHEN I USED TO CONNECT INTERNET FROM MY IPHONE 4S PERSONAL HOTSPOT VIA USB, AN ICON IN THE NETWORK PREFERENCE NAMED "IPHONE" APPEARS.... BUT NOW THIS IS NOT HAPPENING AND I AM NOT ABLE TO CONNECT PERSONAL HOTSPOT VIA USB CABLE. PLEASE HELP ME OUT???

    Please don't shout!   Using all uppercase means shouting on the internet.  If your keyboard is stuck please say so, otherwise people will think you are being obnoxious.
    Now the first question is, when you are saying connecting to personal hotspot, have you always been using the iPhone to connect to the internet?   Are you someplace where the only place to connect is available via tethering to the iPhone's celluar network?  Or do you have other options?

  • My menu bar does not appear at the top of my homepage on a brand new 27" iMac only when i pull up an app. this does not allow me to shut down my mac when all apps are closed nor does it all me to use finder. any help would be awesome

    My menu bar does not appear at the top of my homepage on a brand new 27" iMac only when i pull up an app. this does not allow me to shut down my mac when all apps are closed nor does it all me to use finder. any help would be awesome

    Press the escape (esc) key to exit full-screen mode.

  • How can I find what apple ID I used to register my iMac when I first booted up? I am being told that by using this ID I will be able to go on to the App store and down load iPhoto at no cost. Is this true? My iMac does not have iPhoto resident on it now

    How can I find what apple ID I used to register my iMac when I first booted up? I am being told that by using this ID I will be able to go on to the App store and down load iPhoto at no cost. Is this true? My iMac does not have iPhoto resident on it now and I only purchased my new iMac in December 2012
    Thanks....

    Launch Keychain Access and click on Login in the left hand pane and then on Passwords.  Next do search for Apple in the search field at the top and click on Apple ID Authenicication in the list that comes up.  That will give you the ID no. and password.
    OT

  • When I compose an email in either gmail or yahoo, the cursor lags behind for about 2 seconds. This does not happen when I compose an email with Safari or Chrome. I am using a Mac with Firefox version 3.6.3. Any idea why this happens?

    When I compose an email in either gmail or yahoo, the cursor lags behind for about 2 seconds. This does not happen when I compose an email with Safari or Chrome. I am using a Mac with Firefox version 3.6.3. Any idea why this happens?
    == This happened ==
    Every time Firefox opened

    try
    The Reset Firefox feature can fix many issues by restoring Firefox to its factory default state while saving your essential information.
    Note: ''This will cause you to lose any Extensions, Open websites, and some Preferences.''
    To Reset Firefox do the following:
    #Go to Firefox > Help > Troubleshooting Information.
    #Click the "Reset Firefox" button.
    #Firefox will close and reset. After Firefox is done, it will show a window with the information that is imported. Click Finish.
    #Firefox will open with all factory defaults applied.
    Further information can be found in the [[Reset Firefox – easily fix most problems]] article.
    Did this fix your problems? Please report back to us!
    Thank you.

  • I have copied videos onto an external hard drive. to free memory on my macbook. When I try to delete these I am warned that I will not be able to use this video in existing projects   How do I point iMovie to events in my external  hard drive so I can pl

    I have copied videos onto an external hard drive. to free memory on my macbook. When I try to delete these I am woarned that I will not be able to use this video in existing projects
    How do I point iMovie to events in my external  hard drive so I can play projects which use them?
    MacBook, iMovie 9.0.4

    Hi
    You can do this - by not doing it the way You describe as it will not work.
    a. the external hard disk - MUST BE - Mac OS extended (hfs) formatted -
    UNIX/DOS/FAT32/Mac OS Exchange - will work for most things - BUT NOT FOR VIDEO (iMovie, iDVD or FinalCut doesn't matter)
    b. Do not alter or move any folder named
    • iMovie Event's - or -
    • iMovie Project's
    on DeskTop/Finder - at all
    All moving's of Events and Projects must be done within the iMovie Application - then connections will not break.
    (move them back and see if iMovie remembers them - then do move as described above)
    Yours Bengt W

  • HT204302 i get a message when I plug in my ipod to my laptop saying "cannot use this ipod because apple mobile device is not started" can any one help me with this...I have never had this happen before

    Hello anyone
    I get a message when i plug in my ipod touch saying "cannot use this ipod because apple mobile service is not started" can anyone please help me with this problem...I had this message once before but I forgot how to correct it

    From the More Like This section on the right:
    I get error message when I plug in iPhone 4s saying "This iPhone cannot be used because the Apple Mobile Device service is not started"
    can't get my ipod to connect to tunes error message "cannot be used because the apple mobile device service is not started"  fixes? Using Win XP
    im trying to connect my ipod to itunes and its saying it cannot connect because the "Apple Mobile Device is not started" help
    Or see: iPhone, iPad, iPod touch: How to restart the Apple Mobile Device Service (AMDS) on Windows

  • After several years of use very satisfied with Firefox, recently loaded version (4.0.1) severely slows my browsing, and even my system, especially when there are pictures or videos. I said that this was not the case before and my system is Windows XP SP3.

    After several years of use very satisfied with Firefox, recently loaded version (4.0.1) severely slows my browsing, and even my system, especially when there are pictures or videos. I said that this was not the case before and my system is Windows XP SP3.

    I have had a similar problem with my system. I just recently (within a week of this post) built a brand new desktop. I installed Windows 7 64-bit Home and had a clean install, no problems. Using IE downloaded an anti-virus program, and then, because it was the latest version, downloaded and installed Firefox 4.0. As I began to search the internet for other programs to install after about maybe 10-15 minutes my computer crashes. Blank screen (yet monitor was still receiving a signal from computer) and completely frozen (couldn't even change the caps and num lock on keyboard). I thought I perhaps forgot to reboot after an update so I did a manual reboot and it started up fine.
    When ever I got on the internet (still using firefox) it would crash after anywhere between 5-15 minutes. Since I've had good experience with FF in the past I thought it must be either the drivers or a hardware problem. So in-between crashes I updated all the drivers. Still had the same problem. Took the computer to a friend who knows more about computers than I do, made sure all the drivers were updated, same problem. We thought that it might be a hardware problem (bad video card, chipset, overheating issues, etc.), but after my friend played around with my computer for a day he found that when he didn't start FF at all it worked fine, even after watching a movie, or going through a playlist on Youtube.
    At the time of this posting I'm going to try to uninstall FF 4.0 and download and install FF 3.6.16 which is currently on my laptop and works like a dream. Hopefully that will do the trick, because I love using FF and would hate to have to switch to another browser. Hopefully Mozilla will work out the kinks with FF 4 so I can continue to use it.
    I apologize for the lengthy post. Any feedback would be appreciated, but is not necessary. I will try and post back after I try FF 3.16.6.

  • I have Photoshop CS5, and use windows XP.  I cannot open Bridge from photoshop, whichI have done for years. When I am in Photoshop,when it opens, I always click on the bridge icon at the bottom of the screen, and it puts me into bridge. This is not happen

    I have Photoshop CS5, and use windows XP. I cannot open bridge from photoshop, which I have done for years.  When I am in Photoshop, when it opens, I always click on the bridge icon at the bottom of the screen and it puts me into bridge. This is not happening, the small wheel at the bottom of the screen just keeps spinning. Its like its stuck or caught in a loop. I can't get into bridge. I tried shutting down and starting up again but  the problem remains. Looking for help.  Dan

    Thanks for your response, I was able to open bridge from File-Browse in Bridge.  This worked, but was not able to go back to the way I always opened Bridge.  At least I could get to Bridge and go into Camera Raw. I never tried to open Bridge from the Start menu.  The odd thing about this is, it has happened before, and to get it "unstuck" and working again, I would shut down and restart again in a few minutes, and things would go back to normal.  This time it did not go back to normal after several attempts.  I shut down for about 3-4 hours, restarted, and it seems to be back to normal again. I am not sure if it's a problem that is getting worse each time it happens.       And yes I am using Mini Bridge in photoshop CS5.  Thank you for your help.  Dan

Maybe you are looking for