Why can methods be overriden but attributes can't? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!What is reflection and why is it useful?What is a serialVersionUID and why should I use it?Why can't I use switch statement on a String?Understanding Python super() with __init__() methodsWhy 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 “#”?

Multi tool use
Multi tool use

Maximum summed subsequences with non-adjacent items

Trademark violation for app?

How to write this math term? with cases it isn't working

How come Sam didn't become Lord of Horn Hill?

SF book about people trapped in a series of worlds they imagine

What was the first language to use conditional keywords?

Hangman Game with C++

Time to Settle Down!

Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?

What is the appropriate index architecture when forced to implement IsDeleted (soft deletes)?

How does the secondary effect of the Heat Metal spell interact with a creature resistant/immune to fire damage?

Why weren't discrete x86 CPUs ever used in game hardware?

Is grep documentation about ignoring case wrong, since it doesn't ignore case in filenames?

Why should I vote and accept answers?

Why does it sometimes sound good to play a grace note as a lead in to a note in a melody?

What initially awakened the Balrog?

How fail-safe is nr as stop bytes?

Is it a good idea to use CNN to classify 1D signal?

How does the math work when buying airline miles?

Is it fair for a professor to grade us on the possession of past papers?

When a candle burns, why does the top of wick glow if bottom of flame is hottest?

Is there any word for a place full of confusion?

What do you call the main part of a joke?

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?



Why can methods be overriden but attributes can't?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!What is reflection and why is it useful?What is a serialVersionUID and why should I use it?Why can't I use switch statement on a String?Understanding Python super() with __init__() methodsWhy 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 “#”?



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








14















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
    Mar 27 at 15:49











  • @Noah why did you revert the edited question name? I think the edited title Why can methods be overriden but attributes can't described the content of the question better than the current one. This is important for all other people looking for an answer to their question.

    – Ondra K.
    Mar 28 at 12:20

















14















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
    Mar 27 at 15:49











  • @Noah why did you revert the edited question name? I think the edited title Why can methods be overriden but attributes can't described the content of the question better than the current one. This is important for all other people looking for an answer to their question.

    – Ondra K.
    Mar 28 at 12:20













14












14








14


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 this






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 28 at 20:00









Ondra K.

1,0691926




1,0691926










asked Mar 27 at 14:44









Noah BishopNoah Bishop

1138




1138







  • 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
    Mar 27 at 15:49











  • @Noah why did you revert the edited question name? I think the edited title Why can methods be overriden but attributes can't described the content of the question better than the current one. This is important for all other people looking for an answer to their question.

    – Ondra K.
    Mar 28 at 12:20












  • 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
    Mar 27 at 15:49











  • @Noah why did you revert the edited question name? I think the edited title Why can methods be overriden but attributes can't described the content of the question better than the current one. This is important for all other people looking for an answer to their question.

    – Ondra K.
    Mar 28 at 12:20







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
Mar 27 at 15:49





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
Mar 27 at 15:49













@Noah why did you revert the edited question name? I think the edited title Why can methods be overriden but attributes can't described the content of the question better than the current one. This is important for all other people looking for an answer to their question.

– Ondra K.
Mar 28 at 12:20





@Noah why did you revert the edited question name? I think the edited title Why can methods be overriden but attributes can't described the content of the question better than the current one. This is important for all other people looking for an answer to their question.

– Ondra K.
Mar 28 at 12:20












1 Answer
1






active

oldest

votes


















14














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









    14














    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





























      14














      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



























        14












        14








        14







        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 Mar 27 at 15:15

























        answered Mar 27 at 14:49









        Ondra K.Ondra K.

        1,0691926




        1,0691926





























            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







            XEnLvNb1feNTq1q,0vBorqL el 1cVNISkzg C5qOGjIG
            XfNTRVBfnV4ibauBeCSg5d hIXiMueeOyQwX8h,lC ASjklOHlqvE55r

            Popular posts from this blog

            Football at the 1986 Brunei Merdeka Games Contents Teams Group stage Knockout stage References Navigation menu"Brunei Merdeka Games 1986".

            Solar Wings Breeze Design and development Specifications (Breeze) References Navigation menu1368-485X"Hang glider: Breeze (Solar Wings)"e

            Kathakali Contents Etymology and nomenclature History Repertoire Songs and musical instruments Traditional plays Styles: Sampradayam Training centers and awards Relationship to other dance forms See also Notes References External links Navigation menueThe Illustrated Encyclopedia of Hinduism: A-MSouth Asian Folklore: An EncyclopediaRoutledge International Encyclopedia of Women: Global Women's Issues and KnowledgeKathakali Dance-drama: Where Gods and Demons Come to PlayKathakali Dance-drama: Where Gods and Demons Come to PlayKathakali Dance-drama: Where Gods and Demons Come to Play10.1353/atj.2005.0004The Illustrated Encyclopedia of Hinduism: A-MEncyclopedia of HinduismKathakali Dance-drama: Where Gods and Demons Come to PlaySonic Liturgy: Ritual and Music in Hindu Tradition"The Mirror of Gesture"Kathakali Dance-drama: Where Gods and Demons Come to Play"Kathakali"Indian Theatre: Traditions of PerformanceIndian Theatre: Traditions of PerformanceIndian Theatre: Traditions of PerformanceIndian Theatre: Traditions of PerformanceMedieval Indian Literature: An AnthologyThe Oxford Companion to Indian TheatreSouth Asian Folklore: An Encyclopedia : Afghanistan, Bangladesh, India, Nepal, Pakistan, Sri LankaThe Rise of Performance Studies: Rethinking Richard Schechner's Broad SpectrumIndian Theatre: Traditions of PerformanceModern Asian Theatre and Performance 1900-2000Critical Theory and PerformanceBetween Theater and AnthropologyKathakali603847011Indian Theatre: Traditions of PerformanceIndian Theatre: Traditions of PerformanceIndian Theatre: Traditions of PerformanceBetween Theater and AnthropologyBetween Theater and AnthropologyNambeesan Smaraka AwardsArchivedThe Cambridge Guide to TheatreRoutledge International Encyclopedia of Women: Global Women's Issues and KnowledgeThe Garland Encyclopedia of World Music: South Asia : the Indian subcontinentThe Ethos of Noh: Actors and Their Art10.2307/1145740By Means of Performance: Intercultural Studies of Theatre and Ritual10.1017/s204912550000100xReconceiving the Renaissance: A Critical ReaderPerformance TheoryListening to Theatre: The Aural Dimension of Beijing Opera10.2307/1146013Kathakali: The Art of the Non-WorldlyOn KathakaliKathakali, the dance theatreThe Kathakali Complex: Performance & StructureKathakali Dance-Drama: Where Gods and Demons Come to Play10.1093/obo/9780195399318-0071Drama and Ritual of Early Hinduism"In the Shadow of Hollywood Orientalism: Authentic East Indian Dancing"10.1080/08949460490274013Sanskrit Play Production in Ancient IndiaIndian Music: History and StructureBharata, the Nāṭyaśāstra233639306Table of Contents2238067286469807Dance In Indian Painting10.2307/32047833204783Kathakali Dance-Theatre: A Visual Narrative of Sacred Indian MimeIndian Classical Dance: The Renaissance and BeyondKathakali: an indigenous art-form of Keralaeee