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

                                SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

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