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.

Similar Messages

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

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

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

  • Question about adding keywords to a group of images in Aperture

    Hi all,
    Not sure what I am doing incorrectly, but I am unable to add a keyword to more than 1 image at a time, even though a group of images is selected. So, for example, in Browser view, with 4 images selected, using the keyword HUD, I drag a keyword to one of the selected images, and only the one dragged to gets that keyword, not the others in the group.
    Any ideas?
    Thanks
    Aperture 3.1.1

    Hi Pi,
    Not quite sure what the purpose of that button is.
    You'll laugh about this sometime not too long from now. Sometime, you will have a bunch of photos selected and *not want to change your selection*, but you'll notice that you need to add some metadata or adjust just 1 of those pictures. That's when you use the "primary only". When you find yourself in that situation, it'll be like a "eureka" since you're currently wondering what it's all about.
    nathan

  • What's annoying about Events, Keyword Collections & Move to trash

    Today I was given a project to edit where the Event was already created, the media was optimized, keywords added and keyword collections created to split the media into folders. All I had to do was to sync the 2x cam's to separately recorded audio, and begin grabbing sound bites.
    Nothing unusual so far....
    To start my syncing, I began by finding all the clips from CAM-A and added the keyword SYNC 1 (CAM-A). I also added the separately recorded audio file within this keyword collection. Clicking on the SYNC 1 (CAM-A) keyword collection icon, I highlighted all the clips, right-clicked and chose Syncronize Clips.
    This is what I find annoying: When I choose Syncronize Clips, The synchronized compound clip doesn't automatically appear in my SYNC 1 (CAM-A) keyword collection folder, instead I need to click on the event and add the keyword for it to appeare in that keyword collection. Wouldn't one think that if I chose to create a Syncronized Clip in that keyword collection that FCPX knows thats where I want it to appear...!
    Anyway so in this particular case not all the clips synced, so what I then did was chose the un-synced clip + the audio clip and synced them alone. As i synced these clip separatley, what I was doing was moving the already synced clip to the trash, totally forgetting that these were also being deleted from my main event folder. Boy was I "P***'S'd"
    Again what I found annoying: if you move a clip to the trash in a keyword collection, you actually delete that from the event too. Persionally I'd like to see an option so that you can righ-click and delete a keyword rather than having to twirl down the triangle,  double clicking the keywords to activate the keyword editor, which you then have to select the keyword and hit delete to remove it out of that keyword collection.
    If for arguments sake a clip wouldn't sync, what I then did was find a small snippet of the same audio. I would make a range selection and add a keyword to both the clip and the audio file.
    What I also found annoying: when you open the Syncronized Compound Clip, your unable to stretch the clip to the left, instead I needed to use my "P" tool to move the clip to the right, which then gave me room to streatch the clip to the left.
    Sorry I just had to get that out of my system....

    andynick wrote:
    Yes - and I'm another who loves FCP X . . .
    (but doesn't it drive you round the BEND somitimes)?
    Absolutely Andy.... I won't go into what does and doesn't drive me mad, but your absolutely right, at times I have a smile from ear to ear, and other times I'm left scratching my head and spending valuable time trying to work out a workaround or workflow.
    andynick wrote:
    I think Apple's recommendation of 4GB RAM is a joke.
    True... I spent a day with a colleague editing side by side. He has a 17" MacBook Pro Quad 2.3Ghz with 4GB RAM, and I run on a 17" MacBook Pro Quad 2.3Ghz with 8GB RAM. You wouldn't believe the difference an extra 4GB's of RAM can make, I can only imagine how your system will run on 16GB
    BenB wrote:
    You can right-click a clip to remove keywords, but the only option as present it to remove all keywords at once (Cntr+0). Cmd+K to remove one keyword when you have multiple keywords seems pretty dang easy to me.  If you had more than one Keyword, what would the option in a menu be?  It could make for a very long menu, it'd have to be a dynamic menu, it'd get too convoluted.  So, Contrl+0 or Cmd+K seems pretty easy and efficient to me.
    Ben it was only a suggestion…! Anyway It's probably best we rest this here, it's clear we have different opinions on this one
    BenB wrote:
    As for workflow, no, FCP X is a totally different workflow than any other NLE, period.  You can't compare.  I've been training editors for years who have lots of experience, are from cable networks, and they still walk away faster, more efficient editors.  Thus, I have to say, how long you've been editing, and how many different systems you've use, really doesn't have any bearig when learning something, especially as radicallly different as FCP X.
    Who's comparing?
    The only reason I mentioned what software I've edited on in the past, was so you can see my ability to adapt. FCP X isn't that different! you still work with media, you still need to manage, organise  or name your bins, or in FCPX's terms keyword collections. The list could go on....
    Anyway I'm not here to boast about my experience or the software I've edited on, instead I posted a "personal" view in what I thought would make a nice enhancement, which at the end of the day is just my view…
    BenB wrote:
    I've worked with Larry Jordan a couple of times.  Good tips and tricks stuff.  But the Apple authorized training materials are best for learning from the begining and getting a good handle on things in general.  Nobody (and I mean nobody) knows FCP X like Steve Martin.
    I respect your advise and have just purchased, and am now downloading Steve Martin's tutorials.
    You've got me curious... I'd like to see how different Steve Martin explains FCP X as opposed to Larry Jordan's videos.
    I'll report back on this one as soon as I've viewed them all
    BenB wrote:
    Fill out the feedback page, as I have done a kazillion times already, and let Apple know we need these new Sync'ed Compounds to retian the keywords of their originals.  It would make for a faster workflow.  Seems it'd be easy for them to program in.
    Already done and let's hope so.....
    BenB wrote:
    Here's what I do when sync'ing a bunch of stuff.  I create a Smart Collection that is just a Text parameter that "includes" the word "Compound".  Then when I make the new Compound clips, I can get right to them.  It's a workaround.
    10 points for this tip Ben....
    This is a perfect example where someone (me) expresses his thoughts, then someone (you) finding a solution.
    Love your work mate....!
    BenB wrote:
    I don't do multiple syncs at once, because of bugs, that's all.
    Sorry to sound like a broken record, but an explanation as to why and what bugs would be wonderful.
    Ben, again please don'y take my response as being aggressive. I believe we all come to these discussion forums because some of us have questions, others idea's, and most importantly the ones that give us solutions. That's what makes this community a happy place to come too

  • This keyword problem , how refer to super super class?

    Hello
    I had many times a problem on specifying this keyword as an argument to a constructor
    For example in this case
    package Test;
    public class Model {
        public Model() {
        public void connect(){
            new Thread(){
                public void run(){
                    new TestClass( *this* ).start();
    }bolded this will refer to Thread class and i want it to refer to Model class i mean to the class up one level.
    Is there a way to do that?
    Edited by: neolegionar on Nov 20, 2008 3:16 AM

    Model.this

  • Form Version No in 'About this Application' for LOV forms

    In forms based on the Template qmstpl65.fmb the p_revision parameter is generated and the version number show up in 'about the Application' form.
    Forms based on qmslvt65.fmb does not get the parameter generated (it not in the template), hence UNKNOWN in the version on 'about the Application' form.
    Question is , Is this an oversight or is there a problem with showing versions Number on the 'About this Application' form with LOV Forms ???

    Lucky you, hope you had a great holiday ! Could do with one myself.
    We did find the KEYWORD expansion supplement and it looks just what we want but had problems with loading it.
    I emailed the author over a week ago now and had heard nothing.
    Hope you don't mind, but I will give you the details of the problem in the hope you may be able to help.
    I have downloaded the 'SCM & Oracle Repository - Bulletin' document on Keyword Expansion and the installation zip file of scripts. Which is to allow us to automatically load the SCM version number into objects on check-in.
    When the scripts was run against for repository owner we got an error in jr_keyword.pkb, it is referring to a 'table or view does not exists' called TEMP_LOB which does not exist either on the database or in the scripts.
    PROCEDURE expand_keyword_in_file
    Has a private PROCEDURE expand_blob
    Which has code which refers to the missing table:
    SELECT NVL(MAX(id),0) + 1
    INTO l_temp_blob_id
    FROM temp_lob
    Any ideas about the Table in Question anyone.
    NOTE: we have recently loaded the Designer Patch for Release 4.3 for 6i.

  • Project PSI API checkoutproject is causing exception :LastError=CICOCheckedOutToOtherUser Instructions: Pass this into PSClientError constructor to access all error information

    Hi,
    I'm trying to add a value to the project custom field. After that I'm calling the checkout function before the queueupdate and queuepublish. While calling the checkout  the program is throwing exception as follow:
    The exception is as follows: ProjectServerError(s) LastError=CICOCheckedOutToOtherUser Instructions: Pass this into PSClientError constructor to access all error information
    Please help me to resolve this issue.  I have also tried the ReaProjectentity method i nthe PSI service inrodr to find that project is checked out or not  . Still  the issue is remains . Anyone please help me for this
    flagCheckout = IsProjectCheckedOut(myProjectId);
                        if (!flagCheckout)
                            eventLog.WriteEntry("Inside the updatedata== true and value of the checkout is " + flagCheckout);
                            projectClient.CheckOutProject(myProjectId, sessionId, "custom field update checkout");
    Regards,
    Sabitha

    Standard Information:PSI Entry Point:
    Project User: Service account
    Correlation Id: 7ded1694-35d9-487d-bc1b-c2e8557a2170
    PWA Site URL: httpservername.name/PWA
    SSP Name: Project Server Service Application
    PSError: GeneralQueueCorrelationBlocked (26005)
    Operation could not completed since the Queue Correlated Job Group is blocked. Correlated Job Group ID is: a9dda7f4-fc78-4b6f-ace6-13dddcf784c5. The job ID of the affected job is: 7768f60d-5fe8-4184-b80d-cbab271e38e1. The job type of the affected job is:
    ProjectCheckIn. You can recover from the situation by unblocking or cancelling the blocked job. To do that, go to PWA, navigate to 'Server Settings -> Manage Queue Jobs', go to 'Filter Type' section, choose 'By ID', enter the 'Job Group ID' mentioned in
    this error and click the 'Refresh Status' button at the bottom of the page. In the resulting set of jobs, click on the 'Error' column link to see more details about why the job has failed and blocked the Correlated Job Group. For more troubleshooting you can
    look at the trace log also. Once you have corrected the cause of the error, select the affected job and click on the 'Retry Jobs' or 'Cancel Jobs' button at the bottom of the page.
    This is the error I'm getting now while currently calling the forcehckin, checkout and update. Earlier it was not logging any errors.From this I'm not able to resolve as i cannot filter with job guid

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

  • _name property for this keyword

    When you are using the keyword this inside of an event
    handler it refers to the object that triggered the event.
    For example if OnLoadInit of a sound object is triggered you
    can say
    this.play();
    Is there any way of returning the instance name of this the
    way you can get the name of a movie clip
    ie somemovieclip_mc._name
    It is probably not that simple. If there is a solution it
    probably needs several lines of code.
    However, it would be worth while for a lot of debugging
    purposes.
    Any help would be greatly appreciated.

    Thanks for the quick reply
    Here is an example of the kind of situation I am talking
    about
    this.createEmptyMovieClip("mcSoundHolder",this.getNextHighestDepth());
    //trace("root"+ this._proto_toString);
    var sndAudio:Sound =new Sound(mcSoundHolder);
    var oNameHolder:Object = new Object();
    oNameHolder=this;
    sndAudio.loadSound("scattershot_endings.mp3",false);
    sndAudio.onLoad =function(bSuccess:Boolean ):Void{
    if (bSuccess){
    this.start();
    oNameHolder=this;
    trace (this );
    trace (this );
    yields [object Object]
    I was hoping to get sndAudio
    Alfred

  • Super with This in same constructor

    Hi All,
    I tried to use Super and this keyword in same constructor but it is not working.It gives the exception like constructor call must be the first. I know in base class's constructor super class's constructor should be first statement but also can we not use same class's constructor as second statement in the constructor.?
    Thnkx

    can we not use same class's constructor as second statement in the constructor.?No.
    See the Constructor Rules, reply 2 here: http://forum.java.sun.com/thread.jspa?threadID=721402&messageID=4161149 Your question is covered in point 2.

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

  • Hi team can you assist me about this issue

    Hi team, just wanna tell you this problem if you can help me to fix this.. i buy a brand new video card, but this HP mt 3300 i3 is just a gift from my friend but its already slightly use. getting a problem on graphics card settings, the on board vga is always detected but my graphic card is not. i already change the bios settings, enable and disable something, but nothing happens, this graphic card is working on other pc's but on mine is not. please help me about this issue. thank you so much HP team

    Hi-
    It is not compatible with the Sawtooth.
    The Sawtooth uses PC100 DIMMs.
    The 867 MHz MDD uses PC2100.
    Whether or not that DIMM is Mac compatible is a different question....

  • Memory Speed (MHz) missing in 'About This Mac'

    Hi
    I'm using a Macbook Pro with 10.4.9 and all updates and I recently noticed that the memory speed is missing in the 'About This Mac' window.
    It's saying: Memory 1GB 0 MHz RAM.
    Am I the only one with this problem or is this a bug?

    Please search the discussions before posting, as this topic has already been covered:
    http://discussions.apple.com/thread.jspa?messageID=4489699

Maybe you are looking for

  • Is there any possible to change the shape of the gauge?

    i want to change the shape of the gauge. for example, i hope to chang it from rectangle to rotundity. is there anyone konw about this? thank you for your help . onceaway

  • How to upload video...

    I have some video footage that I would like to upload to "you tube" but when I put the dvd into my MacBook the DVD player opens and I don't see anywhere to save the video to my computer then upload to web? Where am I going wrong? Thanks

  • Sort and compress transport!

    Hi SDN, What is sort and compress of a transport!!

  • Help with small office PBX system.

    Hello all, I'm looking for any help or advice here. We have an old Panasonic PABX, 3 external CO lines and 16 extension lines (only 8 in use). Question 1. We have CO1 connected to the fax/broadband number. C02 and CO3 connected to our other number. H

  • Errorcode 805a0194

    Hello, First of all sorry for my English but I have translated it from dutch by Google. I had a nokia lumia 620 which I had had to take a backup. Now I have to transfer this backup to install my nokia lumia 830. Now there is in store still one action