When to use 'this' keyword

Hi,
I saw some code for a class which extended JFrame
at the end of the constructor it says:
this.setVisible(true);
but of course it works when we have just:
setVisible(true);
I know how to use 'this' in other ways but what is the point of having it here
Cheers
Jim

'this' is used for making differences between class variables and local variables.
public class Test {
private int value;
public void setValue(int value) {
this.value=value;
regards
Stas

Similar Messages

  • 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

  • Can i use " this " keyword in session bean.

    Hi,
    I am working with session beans, in my business logic i need to use " this" keyword,
    but is it possible to use " this" keyword in EJB bean?.

    you can.
    do it !

  • I have macbook pro 2012. I 'm using netbeans 7.2 for using programming. It took about 700mb when I use this application.

    I have macbook pro 2012 4gb ram. I 'm using netbeans 7.2 for using programming. It took about 700mb.

    I'm runing out of memeory when I use other applicaiton such as safari with netbens and inactive memory not clearing when not enough memory for other application.Why is this happing? Does netbens application leak memory?

  • What is repair request? when we use this?

    Hi all,
    what is repair request?
    when actually we use this?
    Thanks& Regards,
    Ravi Alakuntla.

    Hi Ravi,
    When you find some records missing when deltas are running then instead of going for re-init and again deltas you can go for repair full request giving selection conditions for those missing records, without affecting your delta laods.
    Hope it helps,
    Sunil.

  • Using "this" keyword

    Please help me. I didn't find an explanation in manuals or tutorials. Thank you
    //THIS PROGRAM IS WORKING BUT I CANNOT UNDERSTAND IT
    class one{
         public one(){
         System.out.println("This is from constructor");
         //PLEASE MAKE ME UNDERSTAND THIS METHOD IN THE WAY IT IS DECLARED "one two()"!!!!!!!!
         //I'M ALSO CONFUSED ABOUT THE USE OF "THIS" KEYWORD
         one two(){
              System.out.println("This is from method two()");
              return this;
    class From_main{
         public static void main(String[] args){
              one a=new one();
              one b=new one();
              a.two();
              b.two();
         }

    IMHO the trouble with cute trivial Examples like this is that; the names are meaningless and/or tend to confuse
    and they don't represent anything useful that you might do in real life.
    It might help if we renamed the class and methods and added some comments
    class Trivial {
      public Trivial(){
        System.out.println("This is from constructor");
      /** Returns a reference to an instance of this class */
      Trivial getInstance(){
        System.out.println("This is from method getInstance()");
        return this;
    class From_main {
      public static void main(String[] args){
        Trivial a = new Trivial();
        Trivial b = new Trivial();
        Trivial aa = a.getInstance();
        // a and aa point to the same 'Trivial' instance
        if ( a == aa)
          System.out.println("a == aa");
        Trivial bb = b.getInstance();
        // b and bb point to the same 'Trivial' instance
        if ( b == bb)
          System.out.println("b == bb");
    }The method getInstance() is redundant as you have to have a reference to the object
    before you can invoke the method to get a reference to the object.
    There are better ways to illustrate how to use the 'this' keyword.

  • Fn + Spacebar - when to use this?

    I have never seen Fn + Spacebar do anything.  On the paper that came with the ThinkPad, it says this magnifies the screen contents.  But nothing happens when using this with the net, or looking at an image, so when does this work?

    It should've came preloaded. If you installed a stock OS, then it would've been part of the Hotkeys Integrations package.
    It's just how it's done. Better than a huge EXE always staying resident to handle every possible hotkey action.
    W520: i7-2720QM, Q2000M at 1080/688/1376, 21GB RAM, 500GB + 750GB HDD, FHD screen
    X61T: L7500, 3GB RAM, 500GB HDD, XGA screen, Ultrabase
    Y3P: 5Y70, 8GB RAM, 256GB SSD, QHD+ screen

  • What is a Factory method and when to use this concept?

    Could any one please describe what a factory method is and explain how I can use it by giving a simple example

    A Factory Method (sometimes called a "virtual constructor") is a way to avoid hard coding what class is instantiated. Consider:
    DataSource myDataSource = new DataSource();Now, if you want to use some other DataSource in your app, say, an XMLDataSource, then you get to change this code and all subsequent lines that use this, which can be a lot. If, however, you specified and interface for your DataSources, say, IDataSource, and you gave the DataSource class a static "create" method that would take some indication of what sort of DataSource to actually use, then you could write code like:
    IDataSource myDataSource = DataSource.create(dataSourceString);And be able to pass in a dataSourceString describing what DataSource you wanted to use - and not have to recompile. Check out the Java Design Patterns site ( http://www.patterndepot.com/put/8/JavaPatterns.htm )
    Make sense?
    Lee

  • NoClassDefFoundError when I use "package" keyword

    Hi,
    When i put the class into a package, i got the following error message:
    "Exception in thread "main" java.lang.NoClassDefFoundError: Data (wrong name: suncertify/db/Data)"
    But when I delete the "package" keyword, it works fine. why is that?
    Thx.
    adrian

    When you name a package for a class, the fully qualified name for the class is the package name plus the class name, in your case the package name seems to be suncertify.db and the class name is Data so the fully qualified name is suncertify/db/Data (or suncertify.db.Data). If you don't specify a package, then the fully qualified name is just the class name.
    When you launch an application using the java command, you must use the fully qualified class name. In your case, it appears you used "java Data" When the JVM found a Data.class file, it expected a class whose fully qualified name is Data but it found the class suncertify/db/Data - thus the class it found had the wrong name.

  • Type Casting? When to use this concept?

    There is one question bothering me very very much.
    When should I use type casting?
    For example
    ClassNameQ c = (ClassNameQ) ......displayable
    How do I know which 'cast type' to use? Is there a suitable pattern
    we need to follow so that we can know 'Ah this is the cast
    we need to use'
    Please can any one point out which 'Cast type' points needs to be
    followed?
    Regards

    You can Cast an object from any subclass to its superclass,
    or from a superclass to the sublass, if the object is already
    an object of the subclass.
    I have a class named Name:
    public class Name {
    I have a subclass named LastName:
    public class LastName extends Name { [/b]
    And another named FirstName:
    [b]public class FirstName extends Name { [/b]
    I create an object like this:
    [b]LastName ln = new LastName("Johnson");
    Then pass it to a method that can work on all names:
    capitalFirstLetter(ln);
    capitalFirstLetter(Name n) {
    Now n in CapitalFirstLetter can be used only as a Name
    object. Anything specific to the LastName object can't be used.
    So if I need to use things specific to LastName I have to cast
    the object to LastName. There is a problem, however, since this
    method can work on all Names, so I don't know if the Name is
    a LastName or not. The object itself DOES know, however, and
    we can test, so we would cast to a subclass as follows:
    if (n instanceof LastName) {
    LastName ln = (LastName)n;
    ln.addToGeneology();
    } else of (n instanceof FirstName) {
    FirstName fn = (FirstName)n;
    fn.addOccurance();
    Steve

  • What is a factory method? when to use this concept?

    Could any oneplease describe what a factory method is and explain how I can use it by giving a simple example?

    Instead of instantiating a class all over your program you do it in one method that's part of the class. This means the class gets control over the instantiating process, a factory.
    1. You can implement a dispose facility, that is giving back objects that can be reused (when the factory method is called an old object is returned if there is one in store, only if not a new one is instantiated).
    2. An abstract class can have a factory method that returns concrete classes on demand, like
    abstract class Hello {
       static newHello(int id) {  // factory method
          switch (id) {
          case 0: return new Hi();
          case 1: return new Howdy();
          return null;
    public class Hi extends Hello {
    public class Howdy extends Hello {

  • Why runstate.sequencefile.data.seq.mysequence.mystep.result.numeric doesent contain a measurement value when i use this in a post uut callback?

    Hello
    I want to write a csv file witch contains all measurement values and limits from my machine. So i try to give the values in post uut callback to a vi. The limits are working and the csv contains all my limit values but the measurement values are all 0. I used runstate.sequencefile.data.seq.mysequence.mystep.result.numeric
    I would not like to do it with FileGlobals because they are much values.
    Thanks for any advices for this problem.
    Solved!
    Go to Solution.

    There's probably a better way to accomplish what you want.  But to make your life easier I'll give you the hacky solution:
    Use: Runstate.ProcessModelClient.Data.Seq.MyStep.Result.Numeric
    The funny thing is the report should contain all the information you want. I would just create an engine to convert it to your csv look.  If you are using 2012 then this seems like a perfect candidate for a plugin.
    Hope this helps,
    jigg
    CTA, CLA
    teststandhelp.com
    ~Will work for kudos and/or BBQ~

  • 160n halt when connected using this method

    hi there,
    I have the following scenario which cause router 160n to be down
    I have a 160n linksys router which is used as dsl router and directly connected to the internet, and I have another linksys router 160n which is connected to the first  160n router "DSL Router", and linux server (Squid & dhcp) which is also connected directly to the first 160n router " DSL router",
    the problem accurs when I turn my linux srever on, the DSL router start flashing its lights and stop working until I disconnect my server and restart the router.
    I wonder if anybody can help,
    thanks with best regards

    Make sure you have different IP for both routers and they are cascaded correctly.  Search the Linksys web site on how to cascade two routers correctly.

  • I am unable to use the about:permissions command from the url bar, when I use this command receive error message "The url is not found and cannot be loaded".

    This was advertised as a new security feature in the nightly build . Is this true has this security been added to Firefox 5.0 or only certain Firefox builds ?

    Yes, that about:permissions page has recently been added to the Nightly builds (7.0a1), but the Aurora builds (6.0a2) have it as well. I don't think that Firefox 5 will get it.
    * [https://bugzilla.mozilla.org/show_bug.cgi?id=573176 Bug 573176] - Implement Site-Specific Privacy Preferences
    * http://www.mozilla.com/en-US/firefox/channel/

  • Just downloaded trial CS6 Photoshop.  How to start when NEVER used this type of software EVER?

    Downloaded trial CS6 Photoshop to see if it is suitable for our application prior to purchase.  Having NO experience with this type of software, how do you start?  Must be something simple I am missing.  Can't find how to insert picture/photo/text let alone manipulate for desired effect.  PLEASE HELP.  I made it so far as opening a new file WOO HOO.

    Hello and welcome!
    I would first take a look at this beginner's forum FAQ. One of them is how to open a photo in Photoshop. It has step-by-step directions on the subject. 
    To further discover Photoshop:
    AdobeTV has a great set of video tutorials called "Learn Photoshop" .
    Any questions you might have, feel free to post back here.
    enjoy!
    -janelle

Maybe you are looking for

  • How do I upgrade from 7.7 to 8.0 - Can't see in available upgrades S370

    How do you upgrade an Ironport S370 to version 8.x ? We have been advised to update ours to version 8.x however I cannot see anyway of doing this as it's not in avaialable updates the latest we can see is 7.7.0-761 which we are now running. I've look

  • IMovie '11 project file won't open. Please help!

    My daughter put together a short film for a school project last night using iMovie '11 my brand new, out-of-the-box MacBook Pro (running X.6.8). I needed to have the identity updated at work today (including reinstalling my user profile used to creat

  • Get A Mac Ads online

    I have QuickTime Player 6.5.2. I want to watch the happy Get A Mac ads and can't. I get audio, but no video and am told "Software not available on QuickTime Server." This is my home computer, but even on the computers in the office I can't seem to wa

  • How do i get my old firefox bookmarks back after uninstalling firefox

    how do i get my old firefox bookmarks back after uninstalling firefox and then reinstalling it from scratch. I did a system restore, but i only retrieved my old tabs, no book marks :(

  • Fixed vendor in non-catalog PO

    Hi, We are facing some strange issue. We have a field "Vendor" in Basic data and Source of Supply tab in shopping cart. This would have value only in case of catalog item or there is contract or any other source of supply assigned to that item. If th