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

Similar Messages

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

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

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

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

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

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

  • I use SEO quake and love it, but it seems to have lost the Google keywords feature on the Densirty page, is this no longer available ?

    I use SEOquake and love it.
    When you click on the Density icon on the toolbar it takes you to another page showing the keywords on the web page. You used to be able to see the google keywords info on this page including CPC , but this no longer seems to work
    I have tried reloading firefox, but it doesnt make any difference
    Is this feature no longer available?

    PPC applications are not supported in Lion. Must be at leat Office 2008 or 2011. If you have Office 2004 or earlier, you only option to use Microsoft is to upgrade or go back to SL.
    If you have iWorks, you can use Numbers and Pages for microsoft documetns.

  • Updating the photo count for multiple locations of the same keyword

    Is it possible to use a keyword on a photo but have it update other copies of the same keyword in lightroom 2.4? I would like to have linked keywords if this is possible.
    To help understand this better, here is a rough example or what I would like to do.
    I want a generic list of players which in its entirety will contain thousands of names. Then I also want to break those players down into their respective teams/leagues that they played on. This will make the list of players easier to manage when I only have to deal with one team at a time. I also want to seperate by seasons but that is too much for this example. So in my example I have a player who has played in both the AHL and NHL (Daniel Briere).
    Now when I am going through my Flyers photos, I want to keyword a Briere photo. So I drag over the NHL/Philadelphia Flyers/Briere, Daniel keyword. So this gives that keyword a count of 1. I also would like the Briere keyword under Players get updated with a 1. Right now, it won't. How can I link those two? Also, when I go into my Phantoms photos, I see another picture of Briere, I would want to drag over the Teams/AHL/Philadelphia Phantoms/ Briere, Daniel keyword. This would in return update that keyword with a count of 1 and update the Players/Briere, Daniel keyword with a 2 since I now have a single NHL and a single AHL photo of him. Of course I need this behavior to be hierarchial. So if I have a photo of Briere in street clothes, I would want to use the Players/Briere, Daniel keyword. This would then give me a count of 3 but it won't updated the values in NHL and AHL keywords since the Players keyword is in a higher/different location.
    Can this be done?
    Thanks,
    Bob
    P.S. If I made this too confusing, please let me know and I'll try to explain better.
    example of what my keyword list would look like:
    Players
        Briere, Daniel
    Teams
        NHL
            Philadelphia Flyers
                Briere, Daniel
        AHL
            Philadelphia Phantoms
                Briere, Daniel

    You cannot link keywords as you want. Each of those keywords is independent - they just share the same text.
    You can create smart collections which group all occurrences of that name. This is obviously duplication, so you would do it only when you need.
    I suggest you don't try to get too clever with using your keyword hierarchy to represent teams. Instead, use one keyword per individual person, a separate one for each team.You could have a top level keyword teams, and another for people, but don't structure things as you suggest as it leads to confusion about people. When you need to look at one team, use a smart collection that looks for images with Team X, Shot in year Y - the Library Filter  will then break the items down by keyword.
    John

  • Is it possible to make the entire keywords hierachy export in the metadata?

    I have created the following Keyword hierarchy in Aperture:
    Location, Europe, Eastern Europe, Croatia, Dalmatia, Split
    In Aperture I only need to add the bottom level 'Split' as a keyword and when I use the search function and insert a word from any of the higher levels (e.g. Croatia) It finds my picture.
    My problem is that when I export that file the Keywords that get exported in the metadata is only the bottom level I first entered (ie Split). This is no use to me when using the files outside of aperture as I may still want to search at the higher levels.
    Is there anyway to make the entire relevant keyword hierarchy be exported within the metadata without have to go back and add all the levels myself?

    Unless things have changes, keywords are not hierarchical at all as a standard. The hierarchy in Ap is used just for managing keyword purposes only.
    So it works within Ap but not when exported. You will have to assign multiple keywords or reestablish similar scheme in whatever other app that your are exporting the image to.

  • How to reference a class without using the new keyword

    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();

    quedogf94 wrote:
    I need to access some information from a class using the getter, but I don't want to use the new keyword because it will erase the information in the class. How can I reference the class without using the new keyword.
    ContactInfo c = new ContactInfo(); // problem is here because it erases the info in the class
    c.getFirstName();No.
    Using new does not erase anything. There's nothing to erase. It's brand new. It creates a new instance, and whatever that constructor puts in there, is there. If you then change the contents of that instance, and you want to see them, you have to have maintained a reference to it somewhere, and access that instance's state through that reference.
    As already stated, you seem to be confused between class and instance, at the very least.
    Run this. Study the output carefully. Make sure you understand why you see what you do. Then, if you're still confused, try to rephrase your question in a way that makes some sense based on what you've observed.
    (And not that accessing a class (static) member through a reference, like foo1.getNumFoos() is syntactically legal, but is bad form, since it looks like you're accessing an instance (non-static) member. I do it here just for demonstration purposes.)
    public class Foo {
      private static int numFoos; // class variable
      private int x; // instance varaible
      public Foo(int x) {
        this.x = x;
        numFoos++;
      // class method
      public static int getNumFoos() {
        return numFoos;
      // instance method 
      public int getX() {
        return x;
      public static void main (String[] args) {
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ();
        Foo foo1 = new Foo(42);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ();
        Foo foo2 = new Foo(666);
        System.out.println ("Foo.numFoos is " + Foo.getNumFoos ());
        System.out.println ("foo1.numFoos is " + foo1.getNumFoos ());
        System.out.println ("foo1.x is " + foo1.getX ());
        System.out.println ("foo2.numFoos is " + foo2.getNumFoos ());
        System.out.println ("foo2.x is " + foo2.getX ());
        System.out.println ();
    }

  • Warning  on use of the 'subtable' keyword

    I have previously given advice on this list about the use of the "subtable" keyword which could lead to kern pairs being unavailable. If you have used this keyword, please review the following.
    Background.
    Class pairs in a kern feature are compiled as a lookup with a single subtable. The representation of the class pairs for a subtable looks like a big Excel spreadsheet, with all the left side pairs as the titles of the rows, and all the right-side pairs as the titles of the columns, and the kern pair values in the fields. As a result, every left side pair you name is kerned against every right side pair you name. Obviously, most of the fields are 0; there are non-zero values only where you specified a class pair kern value. Less obviously, all glyphs not named in a right side class are automatically assigned to right side class 0. This means that every left side class in the subtable is kerned against every glyph in the font ( with most of the kern values being 0).
    If you have a lot of left and right side class pairs, this subtable can get so large some of the offset values in the compiled lookup exceed the limit of 64K, and the lookup can't be built. The 'subtable' keyword is provided to help with this problem. It forces the class pair lookup to start a new subtable at the point where you put the 'subtable' keyword. If you have any degree of order in your class kern pair definitions, each of the subtables will then have fewer left and right classes, and the overall size of the lookup is smaller.
    My advice on using this keyword is:
    a) use it only if you have to because of a size oveflow problem, and
    b) there is not much use in trying to be smart about where you put it; it is usually simplest to put the first keyword more or less in the middle of the list of the class kern pairs. If this does not shrink the kern lookup enough, then put another 'subtable' keyword in the middle of each half of the class kern pair list, and so on.
    However, I omitted an important warning:
    c) any left side class can be used only within a single subtable.
    This is because each left side class in a subtable is by definition kerned against every right side class, and hence every glyph in the font because of class 0. It follows that a program looking for a kern pair will never look past the first subtable with a left side class containing the left side glyph. Moral: any left side class can be used only within a single subtable. If you put kern class pairs with that left side class in a subsequent subtable ( e.g; after a subtable break), those kern class pairs will never be seen by any program.
    My thanks to Karsten Luecke, whose struggle with an exanple of this problem showed that my previous advice on this list was incomplete.

    You say you're extending JTable but I see no hint of that.
    public class SpecialisedJTable extends JTable
        public SpecialisedJTable(TableModel model)
            super(model);
        public SpecialisedJTable()
            super();
    }

  • Unable to publish in Swf format. Get error message: 'Swf compilation failed. Note: Please verify if any of the actionscript keywords is used as user variable name'. Anyone know how to fix?

    Unable to publish in Swf format. Get error message reads: 'Swf compilation failed. Note: Please verify if any of the actionscript keywords is used as user variable name'. Anyone know how to fix?

    Hi There,
    Can you tell me the Operating System and Captivate version you are using?
    Also can you confirm if you are getting this issue will this one project or all the projects? Try to copy paste this project on a new blank project and then try to publish.
    Regards,
    Mayank

  • Is it possible to auto create albums based off of the saved keywords

    I would like to import my photos but have them organized in albums by the keywords saved in the image tags. Is this possible? I have a large collection that I currently manage on a PC with Abobe Elements 5 and I don't want to have to recreate each album.
    Thanks!
    Larry

    I believe Aperture should import keywords you have attached to images.
    From there, it's really easy to make a smart album based on one or more keywords - you would want to make these folders after import though, then the simple keyword search field will be populated with all possible keywords.

Maybe you are looking for

  • Tabs don't restore even though session restore was selected.

    I have made sure this was not a one-off occurence, and each time my session is not restored. I clicked the 'restore session' pop-up box but this did not work, then I changed my settings to restore tabs automatically (Tools>Options>When firefox starts

  • Update the web links on the Crystal Reports start page?

    Many of the web links on the Crystal Reports start page are now useless and direct to the general "Welcome to the SAP Support World!" page. When will / how can these be updated?

  • ContextMenu Not Displayed in Tree Which is added in popup.

    I have created popup. and added tree in it. Tree has a userdefined contextMenu.But when i right click on item in tree the contextMenu is not displayed.

  • Noisy speakers

    When I wake up my mac opening the clumshell, I hear a short scratchy noise from the speakers, as when you turn on an old radio. I just can't believe it is normal...

  • Dreamweaver CS 5.5 not working with Godaddy FTP with TLS/SSL

    I've upgraded to CS 5.5 and tried to connect to a client's Godaddy account with FTP with TLS/SSL it fails.  Works perfectly with my mac app Transmit every time as it always has.   It doesn't work with implicit or explicit settings with authentication