About the "this" keyword

there's something like this:
public class MainFrame extends JFrame {
PasswordPopup pp = new PasswordPopup(MainFrame.this);
what does MainFrame.this refer to? the MainFrame itself?
if so, what if I use a single "this" instead? thanks

"this" refers to the MainFrame. It should be no different from jus writing "this". However if that line appears within an inner class, using just "this" would refer to the inner class, where MainFrame.this would refer to the outer MainFrame class.

Similar Messages

  • About the volatile keyword

    I am learning about the volatile keyword.
    Does it depend on the VM whether the threads do cache its member variables into memory or not even if the volatile keyword is used? Because in my examlpe below the variable "b" is not volatile and it is beeing used in an infinite loop till some other thread change the variable to false. When it happens, the loop stops and I expected that the variable "b" would only be read once since it is not volatile and the loop would never stop.
    Could somebody explain? :-)
    public class VolatileExample {
        public VolatileExample(){
            T1 t1 = new T1();
            new Thread(t1, "T1").start();
            T2 t2 = new T2(t1);
            new Thread(t2, "T2").start();
        class T1 implements Runnable{
            public boolean b = true; // should be read once if not volatile?
            public T1(){
            public void run() {
                while(b){
                    System.out.println("true");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                System.out.println("false");
        class T2 implements Runnable{
            private T1 r;
            public T2(T1 r){
                this.r = r;
            public void run() {
                try {
                    Thread.sleep(5000);
                    r.b = false; // Here is where I change the other thread´s variable to false
                } catch (InterruptedException ex) {
        public static void main(String[] args){
            new VolatileExample();
    }

    Roxxor wrote:
    Thanks for your answer!
    So a rule of thumb would be: "when sharing a variable among different threads, it should be declared volatile"?I wouldn't say that.
    An absolute rule, however, is, "When sharing a variable among concurrently executing threads, if at least one of the threads will be writing that variable, and if at least one other thread needs to see the writer's update, then you *must* declare the variable volatile or synchronize all access to it."
    That is a bare minimum, of course. By itself, it doesn't guarantee your data will be consistent in a multithreaded context.
    I don't use volatile all that often, because all it does is make writes visible, provide a simple memory barrier, and provide atomicity for doubles and longs. Usually there are more complex requirements that lead to needing synchronization or the classes in java.util.concurrent, and then these end up giving me what volatile would have, plus more.

  • Querstion regarding the "this" keyword

    hi everyone,
    i've doubt regarding the usage of this keyword in the inner classes & static methods. like the following:
    class A {
        int val1 = 0;
        int val2 = 0;
        A() {
            B b = new B();
            C c = new C();
            for(int i=1; i < 11; i++) {
                b.add(i);
                c.add(i);
                System.out.println("Val 1 : " + val1);
                System.out.println("Val 2 : " + val2);
        public static void main(String args[]) {
            new A();
        class B {
            public void add(int val) {
                // the this keyword is used as static variable
                A.this.val1 += val;
        static class C {
            public void add(int val) {
                // the "this" keyword cannot be used
                //A.this.val2 += val;
    }the code doesn't matter what its meant for, i wrote code to explain u my doubt with example.
    so any explanation from ur side, i'm not clear with the this keyword usage.
    thanx

    I am in agreement with trinta, although I think your doubt arises from a lack of understanding of inner classes, not from the use of 'this'. You seem very adept in the use of 'this'.
    Realise that there are 4 categories of nested classes:
    1> Top-level or static nested classes
    These are declared by the static keyword (as in class C in your example). They can be instantiated with or without an instance of the containing class. i.e. using the class names from your example.
    C c = new A.C();
    or
    C c = new instanceOfA.C();
    Since a static nested class does not require an instance of a class, there is no use of the 'this' keyword. There may not be any instance created, if if there was, which one since you don't have to specify which when creating it (see first example code above).
    2> Member Inner Classes
    As in class B in your example. The name should indicate that we think about these classes as members, or part of, the containing instance. Use these classes when it makes no sense for the inner class to exist outside the containing class. Usually these inner classes are designed to be helper classes and often hidden from view. When they aren't, the only way to create new instances of them is through an actual instance of the containing class. i.e. using the class names from your example,
    B b = new instanceOfA.B();
    Note that this code
    B b = new A.B();
    will yield an error. There must be an associated containing class.
    For this reason, the use of 'this' is only appropriate for member classes.
    3> Local Inner Classes
    4> Anonymous Inner Classes
    Not really relevant to this question.

  • What does the this keyword do?

    i don't really understand this code very well, can anyone give me a link or a little explanation that would help me with it? I'm not sure what the this keyword does, and the toString method is puzzling as well.
    thanks.
    public class Friend
         protected String name;
         protected String telephone;
         protected Friend next;
         static Friend list;
         public static void print() {
         Friend friend = list;
         if(friend == null) System.out.println("The list is empty.");
         else do {
         System.out.println(friend);
         friend = friend.next;
         } while (friend != null);
         public Friend(String name, String telephone)
         this.name = name;
         this.telephone = telephone;
         this.next = list;
         list = this;
         public String toString()
         return new String(name+":\t"+telephone);
    class TestFriend
         public static void main(String args[])
         Friend.print();
         new Friend("Anita Murray", "388-1095");
         new Friend("Bill Ross", "283-9104");
         new Friend("Nat Withers", "217-5912");
         Friend.print();
    }

    about the code in post 1, is there any other code
    that could replace what's inside the friend method
    but would still print the same output?
    for example could i replace "this.name = name;" etc
    with anything else?In the context of that constructor, there are two name variables--the parameter and the member variable. The parameter is what was passed into the c'tor, and the member varaible is part of the state of the current object--the object being initialized.
    So, when we just say "name", it means the parameter, and if we want to refer to the name variable that's part of the object, then we say "this.name"--that is, the name varaible belonging to "this" object (the "current" object).
    If there were no local variable or parameter called "name", then instead of "this.name" we could just say "name" to refer to the current object's name variable, because there would be no ambiguity.

  • The this keyword

    I have a vague idea what the this keyword means. Its something to do with inheritance but I'm not sure how this works. For example I've just seen a program as shown below:
    import java.awt.*;
    import java.util.*;
    import java.applet.*;
    import java.text.*;
    import javax.swing.*;
    public class Clock extends JApplet
    implements Runnable {
    private volatile Thread clockThread = null;
    DateFormat formatter; //Formats the date displayed
    String lastdate; //String to hold date displayed
    Date currentDate; //Used to get date to display
    Color numberColor; //Color of numbers
    Font clockFaceFont;
    Locale locale;
    public void init() {
    setBackground(Color.white);
    numberColor = Color.red;
    locale = Locale.getDefault();
    formatter =
    DateFormat.getDateTimeInstance(DateFormat.FULL,
    DateFormat.MEDIUM, locale);
    currentDate = new Date();
    lastdate = formatter.format(currentDate);
    clockFaceFont = new Font("Sans-Serif",
    Font.PLAIN, 14);
    resize(275, 25);
    public void start() {
    if (clockThread == null) {
    clockThread = new Thread(this, "Clock");
    clockThread.start();
    public void run() {
    Thread myThread = Thread.currentThread();
    while (clockThread == myThread) {
    repaint();
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e){ }
    public void paint(Graphics g) {
    String today;
    currentDate = new Date();
    formatter =
    DateFormat.getDateTimeInstance(DateFormat.FULL,
    DateFormat.MEDIUM, locale);
    today = formatter.format(currentDate);
    g.setFont(clockFaceFont);
    //Erase and redraw
    g.setColor(getBackground());
    g.drawString(lastdate, 0, 12);                     
    g.setColor(numberColor);
    g.drawString(today, 0, 12);
    lastdate = today;
    currentDate = null;
    public void stop() {
    clockThread = null;
    Now the line : clockThread = new Thread(this, "Clock");
    What does the this keyword do here?

    Please use code tags as described in Formatting tips
    Classes and Inheritance: Using the this Keyword

  • Using the 'this' keyword

    What is the use of the this keyword:
    import java.util.*;
    public abstract class LegalEntity implements HasAddress{
    private String address;
    private String area;
    private String registrationDate;
    private ArrayList accounts;
    public LegalEntity()
         accounts = new ArrayList();
    public void addAddress(String address){this.address = address;}
    public String getAddress(){return address;}
    public void addAccount(Account account)
         accounts.add(account);
    public ArrayList returnAccounts()
         return accounts;
    }

    This can be used when there are lots of static functions and you want to be sure you are invoking the current objects methods/members.

  • About "this" keyword in constructor

    Hi im new to java... Actually what is the use of "this" keyword? I have tried reference books and internet site still no prevail. As i see there are times when the constructor as
    public hello(int number, number2){
    n = number;
    m = number2;
    without this and some are
    public hello(int number, number2){
    this.number = number;
    this.number2 = number2;
    im so confused please help

    It is a context reference keyword.
    Basically, it is a safety word that tags a specific variable to a method or class.
    In a class, you can have a member variable called aNumber. Now, in method, you could supply an argument that is also called aNumber. Example below:
    public class MyClassExample {
        int aNumber;
        public MyClassExample(int aNumber) {
            aNumber = 1;
    }In the above example, how does Java know what 'aNumber' I am refering to? The class member variable (global variable) or to the method argument variable (local variable)?
    The "this" keyword marks the context to which we refer. If we wanted to tell Java to use the value of the method's argument as the value for our class variable, we would do (this):
    public MyClassExample(int aNumber) {
        aNumber = this.aNumber;
    }Now, what does this really do? Well, Java transparently switches the context for us, but this time we define it.
    When we use the variable name, Java actually records the full context of "MyClassExample.aNumber" with the "MyClassExample.MyClassExample.aNumber"
    See, I bet you never knew that!
    What happens if we want it the other way around, then change which object to place the this keyword to.

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

  • Forward Declaration and "this" keyword

    Consider this code:
    class A {
       private int i = 2 * this.j;  // This will be calculated as 2 * 0 = 0
    //   private int i = 2 * j;  //This code will not compile
       private int j = 20;
    }Why the "this" keyword is required for the j to be accessible? Though it is a forward declaration, what is the significance of "this" which gives visibility to the variable j. Please give some light to this.

    Though it is a forward declaration, what is the significance of "this" which gives
    visibility to the variable jI don't think "this" alters the visibility of j: that is the instance variable j is in scope. However "Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope."
    See "8.3.2.3 Restrictions on the use of Fields during Initialization" http://java.sun.com/docs/books/jls/third_edition/html/classes.html#287410
    Using "this" you have a reference to the object being constructed with the j instance variable sill having its default value of zero.
    Such instance initialisers would appear to be inherently less intelligible than using a constructor.

  • How do I update my old MacBook to the newest operating system, but want to clean it out thoroughly first (without losing my data). How should I best go about doing this?

    Hi everybody. I have a MacBook that's about five years old. I want to buy the newest operating system so that it runs better (because currently it is struggling), however I would like to clean up all the old software before I do that. I want it to be as clean and new as possible before I buy the new operating system, instead of just downloading it ontop of all of the rubbish I must have accumulated. I also want to keep my data (documents, photographs etc). Would anybody be kind enough to provide me with a step-by-step (can be as concise as you like, depending on how much time/effort you have to explain!) guide as to how I might go about doing this myself? Any help would be greatly appreciated. Thank so much guys.

    Step number one - Back up all your important data!
    Seriously, it sounds like you are working without backups. Don't ever do this. Hard drives fail, it is a fact of life. Don't be one of those who get caught without a backup. An external hard drive, burning it all to DVDs, or online backup will save you frustration and money.
    Two - don't expect a new operating system to improve performance. Get the computer running as best as it can before you upgrade. You may need more RAM or a bigger hard drive.

  • HT204053 How can I delete my iCloud account which I do not remember anything about the information that I entered about 4 years ago. It always asks my birth date but it seems I did not enter my correct date how can I bypass this question???

    How can I delete my iCloud account which I do not remember anything about the information that I entered about 4 years ago. It always asks my birth date but it seems I did not enter my correct date how can I bypass this question???

    You cannot delete the account from the server (partly to prevent the username from becoming available again and some-one else using it to pretend to be you).. Having disengaged your devices from it, go to http://icloud.com and delete any data in there such as contacts and calendars. Then just ignore it.

  • HT4623 Is this the most up to date article on up dating the iPhone - it there anything about the problems relating to the up date to OS 6 - my G3 no longer works and Apple seems to have gone to ground.  No Genius bar appointments available for a week!

    Is this the most up to date article on up-dating the iPhone OS - is there anything about the problems relating to the up-date to OS 6 - my G3 no longer works and Apple seems to have gone to ground.  No Genius bar appointments available for a week!

    iOS 7 devices need iTunes 11.1 or newer to sync.  Depending upon your computer and the OS it is running, you may not be able to upgrade to iTunes 11.1 based on the requirements for iTunes 11.1.  What computer and OS are you running your iTunes on?  From the iTunes download pages I see the requiorements are:
    Macintosh System Requirements
    Mac computer with an Intel Core processor
    OS X version 10.6.8 or later
    400MB of available disk space
    Broadband Internet connection to use the iTunes Store
    Windows System Requirements
    PC with a 1GHz Intel or AMD processor and 512MB of RAM
    Windows XP Service Pack 2 or later, 32-bit editions of Windows Vista, Windows 7, or Windows 8
    64-bit editions of Windows Vista, Windows 7, or Windows 8 require the iTunes 64-bit installer
    400MB of available disk space
    Broadband Internet connection to use the iTunes Store

  • TS3579 I found this useful because I did not know about the effect of typing in data and that you could only drag to rearrange the data.  I had typed in data before and this had caused problems but restoring defaults did not cause correct dates to show up

    I found this  (TS3579: If the wrong date or time is displayed in some apps on your Mac Learn about If the wrong date or time is displayed in some apps on your Mac) useful because I did not know about the effect of typing in data and that you could only drag to rearrange the data.  I had typed in data before and this had caused problems but restoring defaults did not cause correct dates to show up in Finder. 

    It sounds like there are a couple things going on here.  First check if you have a successful install of SQL Server, then we'll figure out the connection issues.
    Can you launch SQL Server Configuration Manager and check for SQL Server (MSSQLSERVER) if default instance or SQL Server (other name) if you've configured your instance as a named instance.  Once you find this, make sure the service is started. 
    If not started, try to start it and see if it throws an error.  If you get an error, post the error message your hitting.  If the service starts, you can then launch SSMS and try to connect.  If you have a default instance, you can use the machine
    name in the connection dialog.  Ex:  "COWBOYS" where Cowboys is the machine name.  However, if you named the SQL Server instance during install, you'll need to connect using the machine\instance format.  Ex:  COWBOYS\Romo (where Romo
    is the instance name you set during install).
    You can also look at the summary.txt file in the SQL Server setup error logs to see what happened on the most recent install.  Past install history is archived in the log folder if you need to dig those up to help troubleshoot, but the most
    recent one may help get to the bottom of it if there is an issue with setup detecting a prior instance that needs to be repaired.
    Thanks,
    Sam Lester (MSFT)
    http://blogs.msdn.com/b/samlester
    This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click
    "Mark as Answer" and
    "Vote as Helpful" on posts that help you. This can be beneficial to other community members reading the thread.

  • I bought a second hand MacBook Air and it won't allow me to install updates as up pops the previous owners log in details. How do I go about amending this?

    I bought a second hand MacBook Air and it won't allow me to install updates as up pops the previous owners log in details. How do I go about amending this?

    The seller was remiss in not properly preparing the Mac for sale. That task has now fallen to you. You will encounter continual problems until you perform the following. Ignore references to DVD since the MacBook Air has none.
    If you are unable to do that contact the seller and request instructions, or arrange for its return and a refund of your costs.
    Refer to What to do before selling or giving away your Mac
    If you enabled FileVault, disable it in System Preferences > Security & Privacy.
    "Deauthorize" your iTunes account. Same for Audible if you have one.
    System Preferences > iCloud > de-select "Back to My Mac" and "Find my Mac".
    Sign out of iCloud. Select "Delete from Mac" when it appears.
    Next: Remove all your personal information by completely erasing the Mac's internal storage.
    If your Mac shipped with a grey System Install DVD, start your Mac with that disc inserted in the optical drive while holding the c key to boot from it instead of its internal volume, which should be erased before selling it.
    If your Mac did not ship with discs, boot OS X Internet Recovery:
    using three fingers press and hold the following keys: ⌘(command), option, and R.
    With a fourth finger press the power button to turn on the Mac.
    Keep the other three fingers where they are until you see the "spinning globe" icon.
    This method forces the Mac to download its originally installed OS from Apple's servers, which will not require an Apple ID to install.
    Remove any Open Firmware password if you created one: select Firmware Password Utility from the Utilities menu and remove it.
    Select Disk Utility from the Utilities menu.
    Remove any partitions you may have created.
    Select the Mac's hard disk icon, then select the "Erase" tab.
    Select the "Security Options" button and erase the disk.
    The more "securely" you erase the disk, the longer it will take.
    The fastest method is sufficient since all but the most expensive techniques and equipment will be able to recover securely erased data.
    When it finishes, quit Disk Utility.
    Select Install Mac OS X from the Utilities menu.
    An Apple ID will not be required. If a prompt for an Apple ID appears, return to Step 5.
    Do not create any user accounts.
    When it finishes, shut down the computer.
    If you want to install the bundled apps that were included with your Mac, restart by using your Applications DVD if one was included, and install the bundled apps. Apps bundled with newer Macs that shipped without discs cannot be transferred. Its new owner must purchase them from the Mac App Store using his or her own Apple ID.
    If the Mac is being sold to someone outside the family consider the following additional information:
    System Install DVDs that came with your Mac should remain with it forever, and must be included with the sale.
    Consider including your AppleCare certificate if you bought it, printed documentation, even the box if you still have it. AppleCare stays with the equipment and is transferable.
    Execute a bill of sale showing the Mac's serial number.
    Once no longer in your possession, remove the Mac from your devices in My Support Profile.

  • This morning I ask about the requirement to download the adobe Cs6 before i buy the product and the salesperson told me that i met the requirement for that particular software, so my surprise now when i open the file it says an error because my computer d

    this morning I ask to a sales person about the requirement to download the adobe Creative Cs6 before i buy the product and the salesperson told me that my computer met the requirement for that particular software, so my surprise now when i open the file it says an error because my computer doesn't meet this requirement,  my computer is a OS X 10.5.8 and the requirement  is OS X v10.6.8 or v10.7 what can i do?

    The requirements are online. For the Master Collection the requirements on Macs are:
    Mac OS
    Multicore Intel processor with 64-bit support
    Mac OS X v10.6.8 or v10.7
    4GB of RAM (8GB recommended)
    15.5GB of available hard-disk space for installation; additional free space required during installation (cannot install on a volume that uses a case-sensitive file system or on removable flash-based storage devices)
    Additional disk space required for disk cache, preview files, and other working files; 10GB recommended
    1280×900 display with 16-bit color and 512MB of VRAM; 1680×1050 display required and second professionally calibrated viewing display recommended for Speedgrade
    OpenGL 2.0-capable system
    DVD-ROM drive compatible with dual-layer DVDs (SuperDrive for burning DVDs; Blu-ray burner for creating Blu-ray Disc media)
    Java™ Runtime Environment 1.6
    Eclipse™ 3.7 Cocoa version (for plug-in installation of Flash Builder); the following distributions are supported: Eclipse IDE for Java EE and Java Developers, Eclipse Classic, Eclipse for PHP Developers
    QuickTime 7.6.6 software required for QuickTime features, multimedia, and HTML5 media playbackOptional: Adobe-certified GPU card for GPU-accelerated performance in Premiere Pro; see the latest list of supported cards
    Optional: Adobe-certified GPU card for GPU-accelerated ray-traced 3D renderer in After Effects; see the latest list of supported cards
    Optional: Tangent CP200 family or Tangent Wave control surface for Speedgrade
    Optional: 7200 RPM or faster hard drive (multiple fast disk drives, preferably RAID 0 configured, recommended) for video products
    Broadband Internet connection and registration are required for software activation, validation of subscriptions, and access to online services.* Phone activation is not available.
    You should have been given the correct information. Adobe offers 30-day money back guarantee.
    You can find return information here:
    Return, cancel, or exchange an Adobe order

Maybe you are looking for

  • License Determination

    Hi, I have just started working in SAP GTS Can you please tell me that how License Determination is done for a material? I am getting this error while creating Delivery in ECC that license determination is not done in GTS. Thanks Neha

  • Premiere Pro CS6 on Mac crashes when attempting to capture HDV

    I've seen this topic previously but without an answer and was hoping for an update. I'm using Premiere Pro CS6.0.5 on a MacPro running 10.9.2 The camera is a Sony HDR-FX7. When in the capture window, the camera is recognized. I can rewind and fast fo

  • Why can't I buy the update?

    Alright. I click the 'Update' button on the Summary screen, and a pop-up tells me there is a new software version. I click the 'Learn More' button, so it brings me to the update page that explains the purchase. I click the big blue button that says B

  • Refine edge not working PSE 11

    Hi, I'm getting very frustrated because I cannot figure out the refine edge tool in PSE 11. I have watched the tutorial by Bob Gager and I've read other suggested instructions, AND I do every single thing Bob Gager does in his video, but it's just no

  • HELP ON PDF CUSTOM PAGE SIZE

    Is there any way to save a 5.5" x 8.5" publisher file to the same sized pdf pages....??? I have Windows Vista and Adobe Reader 8. I have a 348 page cookbook ready to publish, but the cookbook publisher wants it saved to pdf in the print-page size....