Why can methods be overriden but attributes can't?What is reflection and why is it useful?What is a serialVersionUID and why should I use it?Understanding Python super() with __init__() methodsHow to know if an object has an attribute in PythonWhy is subtracting these two times (in 1927) giving a strange result?Why don't Java's +=, -=, *=, /= compound assignment operators require casting?Why is char[] preferred over String for passwords?Why is it faster to process a sorted array than an unsorted array?Why not inherit from List<T>?Why is printing “B” dramatically slower than printing “#”?

Is exact Kanji stroke length important?

What does "I’d sit this one out, Cap," imply or mean in the context?

Class Action - which options I have?

Risk of infection at the gym?

Did Dumbledore lie to Harry about how long he had James Potter's invisibility cloak when he was examining it? If so, why?

Lay out the Carpet

How to Reset Passwords on Multiple Websites Easily?

For a non-Jew, is there a punishment for not observing the 7 Noahide Laws?

How did Arya survive the stabbing?

Unreliable Magic - Is it worth it?

Why didn't Theresa May consult with Parliament before negotiating a deal with the EU?

Customer Requests (Sometimes) Drive Me Bonkers!

What is the best translation for "slot" in the context of multiplayer video games?

How do I go from 300 unfinished/half written blog posts, to published posts?

CREATE opcode: what does it really do?

Do the temporary hit points from Reckless Abandon stack if I make multiple attacks on my turn?

Why, precisely, is argon used in neutrino experiments?

How does buying out courses with grant money work?

Are student evaluations of teaching assistants read by others in the faculty?

Sort a list by elements of another list

Closest Prime Number

Do sorcerers' subtle spells require a skill check to be unseen?

How does the UK government determine the size of a mandate?

How do scammers retract money, while you can’t?



Why can methods be overriden but attributes can't?


What is reflection and why is it useful?What is a serialVersionUID and why should I use it?Understanding Python super() with __init__() methodsHow to know if an object has an attribute in PythonWhy is subtracting these two times (in 1927) giving a strange result?Why don't Java's +=, -=, *=, /= compound assignment operators require casting?Why is char[] preferred over String for passwords?Why is it faster to process a sorted array than an unsorted array?Why not inherit from List<T>?Why is printing “B” dramatically slower than printing “#”?













12















I have a class



public class A 
public String attr ="A attribute";
public void method()
System.out.println(this+" , "+this.attr);

public String toString()
return("Object A");




and another class that inherits from it



public class B extends A
public String attr = "B attribute";
public void method()
super.method();

public String toString()
return("Object B");




Note that the method() of B is simply a wrapper for method() of A.



When I run the following code



B b = new B();
b.method();


I get Object B , A attribute as output which means that, this and this.attr accessed different things. Why is that the case?



Shouldn't System.out.println(this) refer to the toString() method of class A ?










share|improve this question



















  • 1





    A modern IDE will have the possibility to show a warning on the second definition of attr that it 'shadows' a similarly named field of a superclass.

    – Mark Jeronimus
    9 hours ago















12















I have a class



public class A 
public String attr ="A attribute";
public void method()
System.out.println(this+" , "+this.attr);

public String toString()
return("Object A");




and another class that inherits from it



public class B extends A
public String attr = "B attribute";
public void method()
super.method();

public String toString()
return("Object B");




Note that the method() of B is simply a wrapper for method() of A.



When I run the following code



B b = new B();
b.method();


I get Object B , A attribute as output which means that, this and this.attr accessed different things. Why is that the case?



Shouldn't System.out.println(this) refer to the toString() method of class A ?










share|improve this question



















  • 1





    A modern IDE will have the possibility to show a warning on the second definition of attr that it 'shadows' a similarly named field of a superclass.

    – Mark Jeronimus
    9 hours ago













12












12








12


6






I have a class



public class A 
public String attr ="A attribute";
public void method()
System.out.println(this+" , "+this.attr);

public String toString()
return("Object A");




and another class that inherits from it



public class B extends A
public String attr = "B attribute";
public void method()
super.method();

public String toString()
return("Object B");




Note that the method() of B is simply a wrapper for method() of A.



When I run the following code



B b = new B();
b.method();


I get Object B , A attribute as output which means that, this and this.attr accessed different things. Why is that the case?



Shouldn't System.out.println(this) refer to the toString() method of class A ?










share|improve this question
















I have a class



public class A 
public String attr ="A attribute";
public void method()
System.out.println(this+" , "+this.attr);

public String toString()
return("Object A");




and another class that inherits from it



public class B extends A
public String attr = "B attribute";
public void method()
super.method();

public String toString()
return("Object B");




Note that the method() of B is simply a wrapper for method() of A.



When I run the following code



B b = new B();
b.method();


I get Object B , A attribute as output which means that, this and this.attr accessed different things. Why is that the case?



Shouldn't System.out.println(this) refer to the toString() method of class A ?







java inheritance attributes this shadowing






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 4 hours ago









Solomon Ucko

7772822




7772822










asked 10 hours ago









Noah BishopNoah Bishop

1036




1036







  • 1





    A modern IDE will have the possibility to show a warning on the second definition of attr that it 'shadows' a similarly named field of a superclass.

    – Mark Jeronimus
    9 hours ago












  • 1





    A modern IDE will have the possibility to show a warning on the second definition of attr that it 'shadows' a similarly named field of a superclass.

    – Mark Jeronimus
    9 hours ago







1




1





A modern IDE will have the possibility to show a warning on the second definition of attr that it 'shadows' a similarly named field of a superclass.

– Mark Jeronimus
9 hours ago





A modern IDE will have the possibility to show a warning on the second definition of attr that it 'shadows' a similarly named field of a superclass.

– Mark Jeronimus
9 hours ago












1 Answer
1






active

oldest

votes


















12














By declaring a method with a same name as parent class, you override it, that is, replace the original behaviour. But if you declare a field with a same name, you effectively hide it, making it inaccessible from that subclass, but only by super.field. See oracle docs on variable hiding, as well as using the keyword super. Note that it is not recommended to use variable hiding, as it creates exactly the kind of confusion you're experiencing.



By calling super.method(), printing this results in calling the toString method, which was in fact overridden - so that's the reason why it prints "Object B", as you've called the method on an instance of B. But the this in this.attr actually refers to the parent object, as you're calling the method from the parent class (by super.method()).






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%2f55380016%2fwhy-can-methods-be-overriden-but-attributes-cant%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    12














    By declaring a method with a same name as parent class, you override it, that is, replace the original behaviour. But if you declare a field with a same name, you effectively hide it, making it inaccessible from that subclass, but only by super.field. See oracle docs on variable hiding, as well as using the keyword super. Note that it is not recommended to use variable hiding, as it creates exactly the kind of confusion you're experiencing.



    By calling super.method(), printing this results in calling the toString method, which was in fact overridden - so that's the reason why it prints "Object B", as you've called the method on an instance of B. But the this in this.attr actually refers to the parent object, as you're calling the method from the parent class (by super.method()).






    share|improve this answer





























      12














      By declaring a method with a same name as parent class, you override it, that is, replace the original behaviour. But if you declare a field with a same name, you effectively hide it, making it inaccessible from that subclass, but only by super.field. See oracle docs on variable hiding, as well as using the keyword super. Note that it is not recommended to use variable hiding, as it creates exactly the kind of confusion you're experiencing.



      By calling super.method(), printing this results in calling the toString method, which was in fact overridden - so that's the reason why it prints "Object B", as you've called the method on an instance of B. But the this in this.attr actually refers to the parent object, as you're calling the method from the parent class (by super.method()).






      share|improve this answer



























        12












        12








        12







        By declaring a method with a same name as parent class, you override it, that is, replace the original behaviour. But if you declare a field with a same name, you effectively hide it, making it inaccessible from that subclass, but only by super.field. See oracle docs on variable hiding, as well as using the keyword super. Note that it is not recommended to use variable hiding, as it creates exactly the kind of confusion you're experiencing.



        By calling super.method(), printing this results in calling the toString method, which was in fact overridden - so that's the reason why it prints "Object B", as you've called the method on an instance of B. But the this in this.attr actually refers to the parent object, as you're calling the method from the parent class (by super.method()).






        share|improve this answer















        By declaring a method with a same name as parent class, you override it, that is, replace the original behaviour. But if you declare a field with a same name, you effectively hide it, making it inaccessible from that subclass, but only by super.field. See oracle docs on variable hiding, as well as using the keyword super. Note that it is not recommended to use variable hiding, as it creates exactly the kind of confusion you're experiencing.



        By calling super.method(), printing this results in calling the toString method, which was in fact overridden - so that's the reason why it prints "Object B", as you've called the method on an instance of B. But the this in this.attr actually refers to the parent object, as you're calling the method from the parent class (by super.method()).







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 10 hours ago

























        answered 10 hours ago









        Ondra K.Ondra K.

        630720




        630720





























            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%2f55380016%2fwhy-can-methods-be-overriden-but-attributes-cant%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

            Isurus Índice Especies | Notas | Véxase tamén | Menú de navegación"A compendium of fossil marine animal genera (Chondrichthyes entry)"o orixinal"A review of the Tertiary fossil Cetacea (Mammalia) localities in wales port taf Museum Victoria"o orixinalThe Vertebrate Fauna of the Selma Formation of Alabama. Part VII. Part VIII. The Mosasaurs The Fishes50419737IDsh85068767Isurus2548834613242066569678159923NHMSYS00210535017845105743

            Wolfenstein 3D Contents Availability Essential improvements Game data Video settings Input settings Audio settings Network VR support Issues fixed Other information System requirements NotesReferences    3D Realms Wolfenstein 3D pageGOG.com Community DiscussionsGOG.com Support PageSteam Community DiscussionsWolfenstein WikiOfficial websiteAmazon.comBethesda.netGamersGateGOG.comGreen Man GamingHumble StoreSteamweb browser versionWolfenstein 3D: Super UpgradesherehereUltraWolfhereWolfMenuECWolf Wolf4SDL WolfGL WinWolf3d NewWolf BetterWolf Sprite Fix and Rotation Project    Wolfenstein 3D VRSplitWolfWolfenstein 3D VRWolfenstein 3D VRWolfenstein 3D VR4DOS command shellFreeDOS's MORE.COMMacBin themthis shim fileWine regeditRELEASE: QUAKE II + III, WOLFENSTEIN 3D, RETURN TO CASTLE WOLFENSTEIN - GOG.com NewsMac Family - Wolfenstein Wiki - WikiaNerdly Pleasures: How many FPS? - DOS Games and Framerates

            Король Коль Исторические данные | Стихотворение | Примечания | Навигацияверсии1 правкаверсии1 правкаA New interpretation of the 'Artognou' stone, TintagelTintagel IslandАрхивировано