Using getters with this. in javaIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?Why use getters and setters/accessors?How do I convert a String to an int in Java?Creating a memory leak with JavaWhy not inherit from List<T>?

How to hide an urban landmark?

Determining fair price for profitable mobile app business

Writing an augmented sixth chord on the flattened supertonic

Why we don’t make use of the t-distribution for constructing a confidence interval for a proportion?

How is the excise border managed in Ireland?

What is the color of artificial intelligence?

Live action TV show where High school Kids go into the virtual world and have to clear levels

How can I get an unreasonable manager to approve time off?

How to handle (one's own) self-harm scars (on the arm), in a work environment?

Electricity free spaceship

Teaching a class likely meant to inflate the GPA of student athletes

Who enforces MPAA rating adherence?

How to safely destroy (a large quantity of) valid checks?

What is the actual quality of machine translations?

Is it expected that a reader will skip parts of what you write?

Warning about needing "authorization" when booking ticket

How come the nude protesters were not arrested?

Why does the Mishnah use the terms poor person and homeowner when discussing carrying on Shabbat?

Can I utilise a baking stone to make crepes?

Which languages would be most useful in Europe at the end of the 19th century?

Is White controlling this game?

Why not invest in precious metals?

Heap allocation on microcontroller

Why was this person allowed to become Grand Maester?



Using getters with this. in java


Is Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?Why use getters and setters/accessors?How do I convert a String to an int in Java?Creating a memory leak with JavaWhy not inherit from List<T>?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I am doing a project for CS, and I just realized that I do not understand the mechanics behind the this. java reference and getters. Specifically, if I have the following:



class Circle
private int radius;


public Circle(int radius)
this.radius = radius;


public int getRadius()
return radius;



  • Why is it that for the constructor, I use this.radius to reference the data field "radius" in the Circle class, but for the constructor, I have this.radius = radius?


  • Does it make a difference whether or not I use the this. so long as it is the only data field named radius?


  • I just tested it on Sublime, and it outputs the same result.

    Just according to my own logic, would it not make more sense to use this.radius to return the radius in the getRadius() getter instead of just return radius because I am referring to the data field in the object Circle?


I really appreciate all the help I can get!










share|improve this question
























  • As your constructor public Circle(int radius)... has parameter name radius which is same like the global parameter name, and you are assigning global parameter(radius) to local parameter (radius) and as there is an ambiguity in names. To simplify we refer Global parameter with this. Like this.radius = radius

    – Kavita_p
    Mar 24 at 19:09


















0















I am doing a project for CS, and I just realized that I do not understand the mechanics behind the this. java reference and getters. Specifically, if I have the following:



class Circle
private int radius;


public Circle(int radius)
this.radius = radius;


public int getRadius()
return radius;



  • Why is it that for the constructor, I use this.radius to reference the data field "radius" in the Circle class, but for the constructor, I have this.radius = radius?


  • Does it make a difference whether or not I use the this. so long as it is the only data field named radius?


  • I just tested it on Sublime, and it outputs the same result.

    Just according to my own logic, would it not make more sense to use this.radius to return the radius in the getRadius() getter instead of just return radius because I am referring to the data field in the object Circle?


I really appreciate all the help I can get!










share|improve this question
























  • As your constructor public Circle(int radius)... has parameter name radius which is same like the global parameter name, and you are assigning global parameter(radius) to local parameter (radius) and as there is an ambiguity in names. To simplify we refer Global parameter with this. Like this.radius = radius

    – Kavita_p
    Mar 24 at 19:09














0












0








0








I am doing a project for CS, and I just realized that I do not understand the mechanics behind the this. java reference and getters. Specifically, if I have the following:



class Circle
private int radius;


public Circle(int radius)
this.radius = radius;


public int getRadius()
return radius;



  • Why is it that for the constructor, I use this.radius to reference the data field "radius" in the Circle class, but for the constructor, I have this.radius = radius?


  • Does it make a difference whether or not I use the this. so long as it is the only data field named radius?


  • I just tested it on Sublime, and it outputs the same result.

    Just according to my own logic, would it not make more sense to use this.radius to return the radius in the getRadius() getter instead of just return radius because I am referring to the data field in the object Circle?


I really appreciate all the help I can get!










share|improve this question
















I am doing a project for CS, and I just realized that I do not understand the mechanics behind the this. java reference and getters. Specifically, if I have the following:



class Circle
private int radius;


public Circle(int radius)
this.radius = radius;


public int getRadius()
return radius;



  • Why is it that for the constructor, I use this.radius to reference the data field "radius" in the Circle class, but for the constructor, I have this.radius = radius?


  • Does it make a difference whether or not I use the this. so long as it is the only data field named radius?


  • I just tested it on Sublime, and it outputs the same result.

    Just according to my own logic, would it not make more sense to use this.radius to return the radius in the getRadius() getter instead of just return radius because I am referring to the data field in the object Circle?


I really appreciate all the help I can get!







java oop getter






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 19:09









YCF_L

35k104687




35k104687










asked Mar 24 at 19:02









Daanyal AkhtarDaanyal Akhtar

11




11












  • As your constructor public Circle(int radius)... has parameter name radius which is same like the global parameter name, and you are assigning global parameter(radius) to local parameter (radius) and as there is an ambiguity in names. To simplify we refer Global parameter with this. Like this.radius = radius

    – Kavita_p
    Mar 24 at 19:09


















  • As your constructor public Circle(int radius)... has parameter name radius which is same like the global parameter name, and you are assigning global parameter(radius) to local parameter (radius) and as there is an ambiguity in names. To simplify we refer Global parameter with this. Like this.radius = radius

    – Kavita_p
    Mar 24 at 19:09

















As your constructor public Circle(int radius)... has parameter name radius which is same like the global parameter name, and you are assigning global parameter(radius) to local parameter (radius) and as there is an ambiguity in names. To simplify we refer Global parameter with this. Like this.radius = radius

– Kavita_p
Mar 24 at 19:09






As your constructor public Circle(int radius)... has parameter name radius which is same like the global parameter name, and you are assigning global parameter(radius) to local parameter (radius) and as there is an ambiguity in names. To simplify we refer Global parameter with this. Like this.radius = radius

– Kavita_p
Mar 24 at 19:09













3 Answers
3






active

oldest

votes


















4














It's because radius is the name of both parameter of constructor and field of the class. To disambiguate those this keyword is used. In case of getter this is not needed, but also won't hurt. Some formatters add this by default, it's equivalent to:



public int getRadius()
return this.radius;






share|improve this answer






























    2














    You don't need this in the constructor if you do not shadow the local name. That is with



    public Circle(int r)
    this.radius = r;



    You can write



    public Circle(int r)
    radius = r;



    The this is only required when it is used to specify which radius you are referring to.






    share|improve this answer






























      0














      Actually when you refer to this.radius that means you use a class field variable. Otherwise (in your code) you may re-assign your radius as an argument in a given constructor that is may be unwanted in your case. To distinguish it you must either use different name of a variable or use this.






      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function ()
        StackExchange.using("externalEditor", function ()
        StackExchange.using("snippets", function ()
        StackExchange.snippets.init();
        );
        );
        , "code-snippets");

        StackExchange.ready(function()
        var channelOptions =
        tags: "".split(" "),
        id: "1"
        ;
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function()
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled)
        StackExchange.using("snippets", function()
        createEditor();
        );

        else
        createEditor();

        );

        function createEditor()
        StackExchange.prepareEditor(
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader:
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        ,
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        );



        );













        draft saved

        draft discarded


















        StackExchange.ready(
        function ()
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55327417%2fusing-getters-with-this-in-java%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        4














        It's because radius is the name of both parameter of constructor and field of the class. To disambiguate those this keyword is used. In case of getter this is not needed, but also won't hurt. Some formatters add this by default, it's equivalent to:



        public int getRadius()
        return this.radius;






        share|improve this answer



























          4














          It's because radius is the name of both parameter of constructor and field of the class. To disambiguate those this keyword is used. In case of getter this is not needed, but also won't hurt. Some formatters add this by default, it's equivalent to:



          public int getRadius()
          return this.radius;






          share|improve this answer

























            4












            4








            4







            It's because radius is the name of both parameter of constructor and field of the class. To disambiguate those this keyword is used. In case of getter this is not needed, but also won't hurt. Some formatters add this by default, it's equivalent to:



            public int getRadius()
            return this.radius;






            share|improve this answer













            It's because radius is the name of both parameter of constructor and field of the class. To disambiguate those this keyword is used. In case of getter this is not needed, but also won't hurt. Some formatters add this by default, it's equivalent to:



            public int getRadius()
            return this.radius;







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 24 at 19:04









            AndronicusAndronicus

            7,54432035




            7,54432035























                2














                You don't need this in the constructor if you do not shadow the local name. That is with



                public Circle(int r)
                this.radius = r;



                You can write



                public Circle(int r)
                radius = r;



                The this is only required when it is used to specify which radius you are referring to.






                share|improve this answer



























                  2














                  You don't need this in the constructor if you do not shadow the local name. That is with



                  public Circle(int r)
                  this.radius = r;



                  You can write



                  public Circle(int r)
                  radius = r;



                  The this is only required when it is used to specify which radius you are referring to.






                  share|improve this answer

























                    2












                    2








                    2







                    You don't need this in the constructor if you do not shadow the local name. That is with



                    public Circle(int r)
                    this.radius = r;



                    You can write



                    public Circle(int r)
                    radius = r;



                    The this is only required when it is used to specify which radius you are referring to.






                    share|improve this answer













                    You don't need this in the constructor if you do not shadow the local name. That is with



                    public Circle(int r)
                    this.radius = r;



                    You can write



                    public Circle(int r)
                    radius = r;



                    The this is only required when it is used to specify which radius you are referring to.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 24 at 19:06









                    Elliott FrischElliott Frisch

                    158k1399193




                    158k1399193





















                        0














                        Actually when you refer to this.radius that means you use a class field variable. Otherwise (in your code) you may re-assign your radius as an argument in a given constructor that is may be unwanted in your case. To distinguish it you must either use different name of a variable or use this.






                        share|improve this answer



























                          0














                          Actually when you refer to this.radius that means you use a class field variable. Otherwise (in your code) you may re-assign your radius as an argument in a given constructor that is may be unwanted in your case. To distinguish it you must either use different name of a variable or use this.






                          share|improve this answer

























                            0












                            0








                            0







                            Actually when you refer to this.radius that means you use a class field variable. Otherwise (in your code) you may re-assign your radius as an argument in a given constructor that is may be unwanted in your case. To distinguish it you must either use different name of a variable or use this.






                            share|improve this answer













                            Actually when you refer to this.radius that means you use a class field variable. Otherwise (in your code) you may re-assign your radius as an argument in a given constructor that is may be unwanted in your case. To distinguish it you must either use different name of a variable or use this.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 24 at 19:09









                            Тимур БибарсовТимур Бибарсов

                            173




                            173



























                                draft saved

                                draft discarded
















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid …


                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.

                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function ()
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55327417%2fusing-getters-with-this-in-java%23new-answer', 'question_page');

                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

                                155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

                                Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?