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.

Similar Messages

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

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

  • Regarding the Belkin Audio Splitter (3.5mm-M/2x3.5mm-F).  Are both sides of this splitter simultaneously bidirectional?

    Regarding the Belkin Audio Splitter (3.5mm-M/2x3.5mm-F).  Are both sides of this splitter simultaneously bidirectional?

    Direct connections are always best, but if you insist:
    Get a Griffin iTrip or replace your radio with one that has AUX inputs and/or Bluetooth.

  • HT1677 In safari browser cookies is working fine. But when I add the browser url to the screen then the cookies concept is not working. In safari setting cookies is always open only. Can you please provide any information regarding to this?

    In safari browser cookies is working fine. But when I add the browser url to the screen then the cookies concept is not working. In safari setting cookies is always open only. Can you please provide any information regarding to this?

    Hello,
    '''Try Firefox Safe Mode''' to see if the problem goes away. [[Troubleshoot Firefox issues using Safe Mode|Firefox Safe Mode]] is a troubleshooting mode that turns off some settings and disables most add-ons (extensions and themes).
    ''(If you're using an added theme, switch to the Default theme.)''
    If Firefox is open, you can restart in Firefox Safe Mode from the Help menu by clicking on the '''Restart with Add-ons Disabled...''' menu item:<br>
    [[Image:FirefoxSafeMode|width=520]]<br><br>
    If Firefox is not running, you can start Firefox in Safe Mode as follows:
    * On Windows: Hold the '''Shift''' key when you open the Firefox desktop or Start menu shortcut.
    * On Mac: Hold the '''option''' key while starting Firefox.
    * On Linux: Quit Firefox, go to your Terminal and run ''firefox -safe-mode'' <br>(you may need to specify the Firefox installation path e.g. /usr/lib/firefox)
    ''Once you get the pop-up, just select "'Start in Safe Mode"''
    [[Image:Safe Mode Fx 15 - Win]]
    '''''If the issue is not present in Firefox Safe Mode''''', your problem is probably caused by an extension, and you need to figure out which one. Please follow the [[Troubleshoot extensions, themes and hardware acceleration issues to solve common Firefox problems]] article to find the cause.
    ''To exit Firefox Safe Mode, just close Firefox and wait a few seconds before opening Firefox for normal use again.''
    When you figure out what's causing your issues, please let us know. It might help others with the same problem.
    Thank you.

  • Where do I - in Callmanager 7x - change a department name and do this have any downside regarding the phones?

    Hi,
    In my Cisco Unified CM Administration System version: 7.0.1.11000-2, I have a lot of different department names and they are all in use.
    Last year one of our departments changed their name, and now I would like to update the old department name to the new department name.
    I have looked everywhere, but I can not find anywhere where I can rename a department, where can I do this? And does it have any downsides regarding the phones and their usage? I can not think that I need to restart or reset all the phones in the department, but I want to be sure before I do anything.
    I know that I can search individual users and phones and rename these, but there must be an automatic approach to rename a department for some 200 users and phones?
    Kind regards,
    Carl-Marius

    Bulk Admin tool.
    Export all users to CSV file.
    Edit the CSV file.
    import the CSV file to CUCM
    run the user import in BULK admin tool.
    It will then update the departments.

  • Have a new mac with OS X 10.9.5 and my CS4 is Not Working anymore. It says to Contact Adobe Support regarding the licence- but that Seems impossible. Any idea how to solve this?

    I Have a new mac book pro with OS X 10.9.5 and now my CS4 is Not Working anymore. It tells me to Contact Adobe Support regarding the licence - but that Seems impossible. Any idea how to solve this?

    Use the web chat and just be patient.
    Mylenium

  • Regarding the article: iTunes Store: Troubleshooting iTunes Match: in my mac iTunes, i don't have a menu option 'view view options'. i do have 'view show view options'. but the resulting popup is different. is this article out of date?

    regarding the article: iTunes Store: Troubleshooting iTunes Match: in my mac iTunes, i don't have a menu option 'view > view options'. i do have 'view > show view options'. but the resulting popup is different. is this article out of date?
    i am troubleshooting iTunes match because it has been days since i uploaded music to mac iTunes and it still has the iCloud status icon for 'waiting'.

    Is there really nobody else with this problem? Really?

  • I have a comment.  I am very upset with Photoshop and all your tutorials regarding the quick select tool.  I have watched many tutorials and read instructions until I am blue in the face.  This tool does not work.  It is all over the place and all of your

    I have a comment.  I am very upset with Photoshop and all your tutorials regarding the quick select tool.  I have watched many tutorials and read instructions until I am blue in the face.  This tool does not work.  It is all over the place and all of your tutorials make it look so simple.  How can you advertise this as a viable tool when it just doesn't work?

    It is all over the place and all of your tutorials make it look so simple.
    This is a user to user Forum, so you are not really addressing Adobe here, even though some Adobe employees thankfully have been dropping by.
    How can you advertise this as a viable tool when it just doesn't work?
    Concluding something does not work because you fail at using it is not necessarily always justified.
    The Quick Selection Tool certainly has limitations, but your post seems to be more about venting than trouble-shooting – otherwise you might have posted an image where you failed to get an expected result.

  • Hi, i was wounding if anyone would help me get information on the company regarding the acquisition of, beats by dre, could someone please help me out as i am doing a college report on this and need some good sources of information

    hi, i was wounding if anyone would help me get information on the company regarding the acquisition of, beats by dre, could someone please help me out as i am doing a college report on this and need some good sources of information

    Try a search with Google.
    Why should we do your homework for you?

Maybe you are looking for