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.

Similar Messages

  • 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 ();
    }

  • 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

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

  • Using the "this" operator to pass variable references among classes and met

    Hi guys still trying to understand how to use the "this" operator
    can some one tell what I am doing wrong or just make this work for me to see how it works.
    public class ReferencePassing
    public static void main(String[]args)
    ReferencePassing rp = new ReferencePassing();
    System.out.println(rp);
    public ReferencePassing()
    HelperObject ho = new HelperObject(this);
    System.out.println(this);
    class HelperObject
    private ReferencePassing MyReferencePassingBuddy;
    public HelperObject (ReferencePassing theRp);
    MyReferencePassingBuddy = theRp;
    print();
    public void print()
    System.out.println(MyReferencePassingBuddy);
    }

    Hi guys still trying to understand how to use the "this" operatorYou're still trying to understand how to write methods and constructors.
    public HelperObject (ReferencePassing theRp);Syntax error at ';'.
    MyReferencePassingBuddy = theRp;
    print();
    public void print()Syntax error: '}' expected.

  • I am trying to use the "This solved my question - 10 points" and the "This helped me - 5 points" but they are NOT doing anything. How do I award the points ?

    I am trying to use the "This solved my question - 10 points" an the "This helped me - 5 points" but they are NOT doing anything. How do I award the points ?

    Are you talking about the "Legend" panel at the right of the window?
    Those text are just help texts explaining the reputation points. You can only award points, if you are the original poster of a question. Then you will see active buttons to award points below the answers you receive. See here for more information: https://discussions.apple.com/static/apple/tutorial/reputation.html
    Regards
    Léonie

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

  • Using the LIKE keyword in a SQL query

    Does anyone have an example using the Database Connectivity Execute Query vi and the LIKE keyword? I would like to do something like:
    SELECT TestNum, TestType FROM tests WHERE DeviceType ='Paul_AF125_Ver1' AND DeviceID = 'Test1' AND (TestType LIKE "Cyclic Voltammetry*")
    It works fine if I say LIKE "Cyclic Voltammetry" (without the *) but if I put the * in there, I get no records.
    I'm using Microsofts SQL Server Desktop Engine (comes with Access).
    Thanks,
    Paul

    Paul-
    Thank you for contacting National Instruments. I don't have an example program, but I did find some information for you.
    LIKE - similar to.
    Using the LIKE command, you can use the wildcard symbol %. To find names starting with J : names LIKE 'J%'; Ending in s ? name LIKE '%S'; You can use more than one % charactor too : names LIKE '%sam%'; Also, LIKE is not case sensitive.
    What you have written, may work if you change the wildcard syntax from * to %.
    -Erik

  • Use of this. keyword

    can anyone explain "this" in a clear concise way? I do know that its used to specify a value in a particular instance, but things like
    this.x = x;
    ,confuse me a bit . Isn't the x already defined as x ?

    thanks ever so much..so its the newly constructed x
    that is being assigned the value that is being passed,
    is that it?This is maybe clearer. The x (at the class level) is assigned the value of i (past as parameter to the constructor).
    class Example {
        private int x;
        public Example (int i) {
            x = i;
    }The reason for the use of this.x=x is I think that people don't want to invent two names for the same thing. You see this too,
    class Example {
        private int x;
        public Example (int _x) {
            x = _x; // serves the same purpose as this.x = x

  • How to require field input using the this.mailDoc function

    I have a this.mailDoc script in a form I'm putting together. It's working fine, but what I'm needing are instructions on how to require certain fields to be filled in before the this.mailDoc can execute. I know how to do this using the stock Submit Form button, but that won't work for me in my particular situation. Thoughts?

    You have to use your own validation function to make sure the required
    fields are filled-in.
    I've posted some code that does this on these forums a while ago... Try
    searching for "validate required fields".

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

  • Not getting the use of 'this' keyword in constructor as shortcut approach.

    class Box{
    int width;
    int height;
    int depth;
    Box(){ //no-arg constructor
    Width =1;
    Height = 2;
    Depth = 3;
    Box(int width){
    this.width = width;
    height = 2;
    depth = 3;
    Box(int width, int height){
    this.width = width;
    this.height = height;
    depth = 3;
    /*Box(int width, int height, int depth){
    this.width = width;
    this.height = height;
    this.depth = depth;
    *//short cut approach*
    *Box(int width, int height, int depth){*
    this(width, height); //calls matching constructor from the same class
    this.depth = depth;
    Box(Box b){
    this.width = b.width;
    this.height = b.height;
    this.depth = b.depth;
    public class ConstructorDemo {
    public static void main(String[] args) {
    Box b1 = new Box(1,2,3);
    Box b2 = new Box(b1);
    In the above example, 'this' pointing to current object is understood but
    this(width, height); is used instead of this.width=width; this.height=height;
    how can it be shortcut when we have declared constructors ? And really how its so useful in a big code?
    Edited by: 1010533 on Jun 7, 2013 12:54 PM

    Welcome to the forum!
    >
    class Box{
    int width;
    int height;
    int depth;
    Box(){ //no-arg constructor
    Width =1;
    Height = 2;
    Depth = 3;
    Box(int width){
    this.width = width;
    height = 2;
    depth = 3;
    Box(int width, int height){
    this.width = width;
    this.height = height;
    depth = 3;
    /*Box(int width, int height, int depth){
    this.width = width;
    this.height = height;
    this.depth = depth;
    //short cut approach
    Box(int width, int height, int depth){
    this(width, height); //calls matching constructor from the same class
    this.depth = depth;
    Box(Box b){
    this.width = b.width;
    this.height = b.height;
    this.depth = b.depth;
    public class ConstructorDemo {
    public static void main(String[] args) {
    Box b1 = new Box(1,2,3);
    Box b2 = new Box(b1);
    In the above example, 'this' pointing to current object is understood but
    this(width, height); is used instead of this.width=width; this.height=height;
    how can it be shortcut when we have declared constructors ?
    >
    Shortcut? Who said it is a shortcut?
    >
    And really how its so useful in a big code?
    >
    EXTREMELY useful - especially in 'big code' (whatever you mean by that).
    Constructors are meant to create VALID instances. The business rules for creating a valid instance may not be as simple as your example.
    Ideally code should be written once and used often. The use of constructors is no different.
    Once you have a contructor for a given set of arguments you should use it if you need to construct an instance like that.
    So when you need a constructor that uses those same arguments and then some additional ones your new constructor should call the existing constructor and should then apply the new logic needed for the new constructor.
    That is important because it means that the business logic needed for those two arguments is only implemented in ONE place. That logic might be very complicated and there is no valid reason to duplicate it.
    Once you have a piece of code that works reuse it whenever possible.

  • Trouble using the "into" keyword in a select statement

    I was able to run the below query fine:
    SELECT QTTYP.Qt_Grp, 
    CFQR.ReferralCode, 
    CFQR.RecKey, 
    Count(CFQR.RecKey) AS Cnt
    FROM [HR_DEV_DM].[CFQ_TEST].CFQ_Referrals as CFQR 
    INNER JOIN [HR_DEV_DM].[CFQ_TEST].t_Qt_Typs as QTTYP 
    ON CFQR.QuoteType = QTTYP.Qt_Grp
    WHERE (((CFQR.QuoteType) Not In ('AUTO/CYCLE','COMMERCIAL','CYCLE')) 
    AND ((CFQR.QuoteDate)>=DateAdd("m",-15,CONVERT (date, GETDATE())))
    AND ((CFQR.RecCntdAsRefrl)=1))
    GROUP BY QTTYP.Qt_Grp, 
    CFQR.ReferralCode, 
    CFQR.RecKey, 
    CFQR.RecChangeID
    HAVING (((Count(CFQR.RecKey))>1) AND ((CFQR.RecChangeID) Is Null)) 
    OR (((Count(CFQR.RecKey))>1) 
    AND ((CFQR.RecChangeID) Not In (1035)))
    ORDER BY QTTYP.Qt_Grp, CFQR.RecKey;
    I am trying to add the output columns into a temp table. But when I add the "into" statement, as shown below, it gives me errors:
    SELECT QTTYP.Qt_Grp, 
    CFQR.ReferralCode, 
    CFQR.RecKey, 
    Count(CFQR.RecKey) AS Cnt
    FROM [HR_DEV_DM].[CFQ_TEST].CFQ_Referrals as CFQR 
    into I_Dup_RecKey_Check_01
    INNER JOIN [HR_DEV_DM].[CFQ_TEST].t_Qt_Typs as QTTYP 
    ON CFQR.QuoteType = QTTYP.Qt_Grp
    WHERE (((CFQR.QuoteType) Not In ('AUTO/CYCLE','COMMERCIAL','CYCLE')) 
    AND ((CFQR.QuoteDate)>=DateAdd("m",-15,CONVERT (date, GETDATE())))
    AND ((CFQR.RecCntdAsRefrl)=1))
    GROUP BY QTTYP.Qt_Grp, 
    CFQR.ReferralCode, 
    CFQR.RecKey, 
    CFQR.RecChangeID
    HAVING (((Count(CFQR.RecKey))>1) AND ((CFQR.RecChangeID) Is Null)) 
    OR (((Count(CFQR.RecKey))>1) 
    AND ((CFQR.RecChangeID) Not In (1035)))
    ORDER BY QTTYP.Qt_Grp, CFQR.RecKey;
    Errors:
    Msg 156, Level 15, State 1, Line 7
    Incorrect syntax near the keyword 'into'.
    Msg 102, Level 15, State 1, Line 11
    Incorrect syntax near 'CFQR'.
    Msg 102, Level 15, State 1, Line 18
    Incorrect syntax near 'Count'.
    Msg 102, Level 15, State 1, Line 19
    Incorrect syntax near 'Count'.
    Please help.....

    You have put INTO into the wrong place :
    SELECT QTTYP.Qt_Grp,
    CFQR.ReferralCode,
    CFQR.RecKey,
    Count(CFQR.RecKey) AS Cnt
    into I_Dup_RecKey_Check_01
    FROM CFQ_Referrals as CFQR
    INNER JOIN t_Qt_Typs as QTTYP
    ON CFQR.QuoteType = QTTYP.Qt_Grp
    WHERE (((CFQR.QuoteType) Not In ('AUTO/CYCLE','COMMERCIAL','CYCLE'))
    AND ((CFQR.QuoteDate)>=DateAdd("m",-15,CONVERT (date, GETDATE())))
    AND ((CFQR.RecCntdAsRefrl)=1))
    GROUP BY QTTYP.Qt_Grp,
    CFQR.ReferralCode,
    CFQR.RecKey,
    CFQR.RecChangeID
    HAVING (((Count(CFQR.RecKey))>1) AND ((CFQR.RecChangeID) Is Null))
    OR (((Count(CFQR.RecKey))>1)
    AND ((CFQR.RecChangeID) Not In (1035)))
    ORDER BY QTTYP.Qt_Grp, CFQR.RecKey;

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

  • Which cache the Formula Engine will use in this case?

    Say that a MDX query contains:
    ❶a calculated measure defined in the targeted cube, ❷and another
    WITH MEMBER.
    Which cache the Formula Engine will use in this case:
    ❶Query,
    ❷Global, or
    ❸both (query & global)? and why? .... illustrate as possible please.

    Thanks Elvis ... but
    ❶ doesn't your reply, especially this part:
    ...But if we use WITH MEMBER keyword to define a calculated measure, it's the Storage Engine cache and not the Formula Engine cache....
    contradict with Microsoft's white
    paper: SQL
    Server 2008 R2 Analysis Services Performance Guide? ... check the figure below please:
    this is in page 36, where they are talking about the Formula Engine (or Query Processor, as they sometimes refer to it) types of cache. note the highlighted, they are saying that using the "WITH keyword within a query" forces the use of the "Query
    Context" which is one of the formula engine cache (as they said).
    Actually I've asked the main question because of this part of the same 36 page:
    I wanted to know
    ❷ what will happen to the calculated measures (those defined in the cube) if combined with another calculated members defined using the WITH keyword, in the same query? are they going to be recalculated even if they are already
    exist in the global cache?

Maybe you are looking for

  • BlackBerry doesn't want my money.

    I am incredibly amazed by BlackBerry's sales policy in England. Here's the story. I live in Sheffield UK and it was time for me to buy a new phone since my 3 year old Motorola has started to let me down. I am the type of person that does a proper res

  • May I Safely Delete My Older Version of Microsoft Office?

    I recently installed Mavericks on my MacBook Pro.  Mavericks does not support Microsoft Office 2004 for Mac, which I was using before installing Mavericks.  Therefore, I have purchased and installed Microsoft Office 2011 for Mac.  In "Applications" i

  • Can't upgrade to AIR 2. Same old "administrator" error.

    On Windows XP SP3, attempting to upgrade from Pandora Player, Adobe AIR 1.5.3.9130 to 2.0.2.12610 I get this error. An error occurred while installing Adobe AIR. Installation may not be allowed by your administrator. I download the installer and try

  • Can I renumber imported files by date?

    I have noticed that in LR 3.2 if I import from my d90 across multiple dates, the numbering continues to escalate even though the date has changed. I would like to have the photos from each date start with a 1, and import multiple shooting dates in th

  • Input Search criteria gets cleared on searching in Search Region

    In a pageA I have a search region, this search region has 2 date fields. I have a return link on pageA that directs to pageB. Another button on pageB directs to pageA. For every page redirection, we have retainAM='Y', due to this the search criterial