Unclear about dynamic bindingEfficiency of Java “Double Brace Initialization”?Getting value to display for Java CurrentAccount classStatic Vs. Dynamic Binding in JavaClone a Singleton objectIs it possible to write a program in Java without main() using JDK 1.7 or higher?Overriding private methods in (non-)static classesExecutorService workStealingPool and cancel methodJava - Method executed prior to Default Constructorconfusion about upcasting vs dynamic bindingjava exception - why does it catch?

How to manage monthly salary

Denied boarding due to overcrowding, Sparpreis ticket. What are my rights?

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

What do you call something that goes against the spirit of the law, but is legal when interpreting the law to the letter?

Is this food a bread or a loaf?

If a centaur druid Wild Shapes into a Giant Elk, do their Charge features stack?

Pristine Bit Checking

Why airport relocation isn't done gradually?

Is Social Media Science Fiction?

Copycat chess is back

Symmetry in quantum mechanics

Map list to bin numbers

Email Account under attack (really) - anything I can do?

Is ipsum/ipsa/ipse a third person pronoun, or can it serve other functions?

Is there a name of the flying bionic bird?

Are objects structures and/or vice versa?

Ideas for 3rd eye abilities

What is the command to reset a PC without deleting any files

Does the average primeness of natural numbers tend to zero?

"My colleague's body is amazing"

What to wear for invited talk in Canada

I’m planning on buying a laser printer but concerned about the life cycle of toner in the machine

Manga about a female worker who got dragged into another world together with this high school girl and she was just told she's not needed anymore

Is domain driven design an anti-SQL pattern?



Unclear about dynamic binding


Efficiency of Java “Double Brace Initialization”?Getting value to display for Java CurrentAccount classStatic Vs. Dynamic Binding in JavaClone a Singleton objectIs it possible to write a program in Java without main() using JDK 1.7 or higher?Overriding private methods in (non-)static classesExecutorService workStealingPool and cancel methodJava - Method executed prior to Default Constructorconfusion about upcasting vs dynamic bindingjava exception - why does it catch?






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








16















I am not understanding the concept of dynamic binding and overriding properly:



Here is some code:



class Cake 
public void taste (Cake c)
System.out.println("In taste of Cake class");



class ChocolateCake extends Cake
public void taste(Cake c)
System.out.println("In taste (Cake version) of ChocolateCake class");

public void taste(ChocolateCake cc)
System.out.println("In taste (ChocolateCake version) of ChocolateCake class");




public static void main(String[] args)

ChocolateCake cc = new ChocolateCake();
Cake c = new ChocolateCake();
Cake c1 = new Cake();
Cake c2 = new ChocolateCake();

c1.taste(cc);
c1.taste(c);

c2.taste(cc);
c2.taste(c);



I expected:



In taste of Cake class
In taste of Cake class
In taste (ChocolateCake version) of ChocolateCake class" <----
In taste (Cake version) of ChocolateCake class


Actual:



In taste of Cake class
In taste of Cake class
In taste (Cake version) of ChocolateCake class <----
In taste (Cake version) of ChocolateCake class


If the object is of type ChocolateCake and I call cc which is also ChocolateCake, how come the compiler shows it's getting Cake as a parameter?










share|improve this question
























  • Please consider accepting an answer by clicking on that checkmark.

    – Sweeper
    Apr 1 at 8:35

















16















I am not understanding the concept of dynamic binding and overriding properly:



Here is some code:



class Cake 
public void taste (Cake c)
System.out.println("In taste of Cake class");



class ChocolateCake extends Cake
public void taste(Cake c)
System.out.println("In taste (Cake version) of ChocolateCake class");

public void taste(ChocolateCake cc)
System.out.println("In taste (ChocolateCake version) of ChocolateCake class");




public static void main(String[] args)

ChocolateCake cc = new ChocolateCake();
Cake c = new ChocolateCake();
Cake c1 = new Cake();
Cake c2 = new ChocolateCake();

c1.taste(cc);
c1.taste(c);

c2.taste(cc);
c2.taste(c);



I expected:



In taste of Cake class
In taste of Cake class
In taste (ChocolateCake version) of ChocolateCake class" <----
In taste (Cake version) of ChocolateCake class


Actual:



In taste of Cake class
In taste of Cake class
In taste (Cake version) of ChocolateCake class <----
In taste (Cake version) of ChocolateCake class


If the object is of type ChocolateCake and I call cc which is also ChocolateCake, how come the compiler shows it's getting Cake as a parameter?










share|improve this question
























  • Please consider accepting an answer by clicking on that checkmark.

    – Sweeper
    Apr 1 at 8:35













16












16








16


1






I am not understanding the concept of dynamic binding and overriding properly:



Here is some code:



class Cake 
public void taste (Cake c)
System.out.println("In taste of Cake class");



class ChocolateCake extends Cake
public void taste(Cake c)
System.out.println("In taste (Cake version) of ChocolateCake class");

public void taste(ChocolateCake cc)
System.out.println("In taste (ChocolateCake version) of ChocolateCake class");




public static void main(String[] args)

ChocolateCake cc = new ChocolateCake();
Cake c = new ChocolateCake();
Cake c1 = new Cake();
Cake c2 = new ChocolateCake();

c1.taste(cc);
c1.taste(c);

c2.taste(cc);
c2.taste(c);



I expected:



In taste of Cake class
In taste of Cake class
In taste (ChocolateCake version) of ChocolateCake class" <----
In taste (Cake version) of ChocolateCake class


Actual:



In taste of Cake class
In taste of Cake class
In taste (Cake version) of ChocolateCake class <----
In taste (Cake version) of ChocolateCake class


If the object is of type ChocolateCake and I call cc which is also ChocolateCake, how come the compiler shows it's getting Cake as a parameter?










share|improve this question
















I am not understanding the concept of dynamic binding and overriding properly:



Here is some code:



class Cake 
public void taste (Cake c)
System.out.println("In taste of Cake class");



class ChocolateCake extends Cake
public void taste(Cake c)
System.out.println("In taste (Cake version) of ChocolateCake class");

public void taste(ChocolateCake cc)
System.out.println("In taste (ChocolateCake version) of ChocolateCake class");




public static void main(String[] args)

ChocolateCake cc = new ChocolateCake();
Cake c = new ChocolateCake();
Cake c1 = new Cake();
Cake c2 = new ChocolateCake();

c1.taste(cc);
c1.taste(c);

c2.taste(cc);
c2.taste(c);



I expected:



In taste of Cake class
In taste of Cake class
In taste (ChocolateCake version) of ChocolateCake class" <----
In taste (Cake version) of ChocolateCake class


Actual:



In taste of Cake class
In taste of Cake class
In taste (Cake version) of ChocolateCake class <----
In taste (Cake version) of ChocolateCake class


If the object is of type ChocolateCake and I call cc which is also ChocolateCake, how come the compiler shows it's getting Cake as a parameter?







java






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 30 at 22:01









Peter Mortensen

13.9k1987113




13.9k1987113










asked Mar 30 at 17:54









coding_potatocoding_potato

833




833












  • Please consider accepting an answer by clicking on that checkmark.

    – Sweeper
    Apr 1 at 8:35

















  • Please consider accepting an answer by clicking on that checkmark.

    – Sweeper
    Apr 1 at 8:35
















Please consider accepting an answer by clicking on that checkmark.

– Sweeper
Apr 1 at 8:35





Please consider accepting an answer by clicking on that checkmark.

– Sweeper
Apr 1 at 8:35












3 Answers
3






active

oldest

votes


















9














This is because Java uses both static and dynamic binding to choose a method to call in this case.



The line in question is this, right?



c2.taste(cc);


The compiler first chooses which method to call (static binding). Since c2 is of compile time type Cake, the compiler only sees the taste(Cake) method. So it says "call taste(Cake)".



Now at runtime, the runtime needs to choose which implementation of taste(Cake) to call, depending on the runtime type of c2. This is dynamic binding. Does it choose the one in Cake? Or the one in ChocolateCake? Since c2 is of runtime type ChocolateCake, it calls the implementation of taste(Cake) in ChocolateCake.



As you can see, the method that you thought would be called - taste(ChocolateCake) - is not even mentioned! This is because that is a different overload of the taste method, and because it is in the ChocolateCake class, which the compiler can't see. Why can't the compiler see? Because c2 is of compile time type Cake.



In short, the compiler decides which overload, the runtime decides which implementation.



Responding to your statement:




if the object is of type ChocolateCake ...




Only you know the object is of type ChocolateCake. The compiler does not. It only knows c2 is of type Cake because that's what its declaration says.






share|improve this answer






























    8














    Since the reference type of the c2 variable is Cake the taste method having the Cake type parameter will be called.



    This is because the Cake type does not have the taste method which takes a ChocolateCake instance, so you can't invoke that method from a Cake type reference variable.



    Now secondly, in Java due to the mechanism of runtime polymorphism the overridden taste method of the ChocolateCake is being called instead of the version declared in the parent Cake class. This is due to fact at runtime the object which the Cake reference is pointing to, will be examined and the taste version of that particular instance will be invoked.



    So due to the combination of these two effects you see that output.



    If you change the reference type of c2 to ChocolateCake you would see that the output is:



    In taste (ChocolateCake version) of ChocolateCake class 


    when you invoke c2.taste(cc);, since now both the compiler and runtime agrees to call that taste(ChocolateCake cc) method in particular.






    share|improve this answer
































      0














      In Java the decision which methodset to call in case of c2.taste(cc) is performed at compile-time based on the compile-time type of c2. The compile-time type of c2 is Cake, which means that any method call on c2 is searching just class Cake and its superclasses, and isn't searching any subclasses of Cake (namely ChocolateCake) even if all the subclasses are visible to the compiler.



      Languages performing fully dynamic method resolution at runtime based on the actual runtime types of the receiver&arguments, which would make c2.taste(cc) be resolved into ChocolateCake.taste(ChocolateCake cc), are rare because it negatively affects runtime performance.






      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%2f55434188%2funclear-about-dynamic-binding%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









        9














        This is because Java uses both static and dynamic binding to choose a method to call in this case.



        The line in question is this, right?



        c2.taste(cc);


        The compiler first chooses which method to call (static binding). Since c2 is of compile time type Cake, the compiler only sees the taste(Cake) method. So it says "call taste(Cake)".



        Now at runtime, the runtime needs to choose which implementation of taste(Cake) to call, depending on the runtime type of c2. This is dynamic binding. Does it choose the one in Cake? Or the one in ChocolateCake? Since c2 is of runtime type ChocolateCake, it calls the implementation of taste(Cake) in ChocolateCake.



        As you can see, the method that you thought would be called - taste(ChocolateCake) - is not even mentioned! This is because that is a different overload of the taste method, and because it is in the ChocolateCake class, which the compiler can't see. Why can't the compiler see? Because c2 is of compile time type Cake.



        In short, the compiler decides which overload, the runtime decides which implementation.



        Responding to your statement:




        if the object is of type ChocolateCake ...




        Only you know the object is of type ChocolateCake. The compiler does not. It only knows c2 is of type Cake because that's what its declaration says.






        share|improve this answer



























          9














          This is because Java uses both static and dynamic binding to choose a method to call in this case.



          The line in question is this, right?



          c2.taste(cc);


          The compiler first chooses which method to call (static binding). Since c2 is of compile time type Cake, the compiler only sees the taste(Cake) method. So it says "call taste(Cake)".



          Now at runtime, the runtime needs to choose which implementation of taste(Cake) to call, depending on the runtime type of c2. This is dynamic binding. Does it choose the one in Cake? Or the one in ChocolateCake? Since c2 is of runtime type ChocolateCake, it calls the implementation of taste(Cake) in ChocolateCake.



          As you can see, the method that you thought would be called - taste(ChocolateCake) - is not even mentioned! This is because that is a different overload of the taste method, and because it is in the ChocolateCake class, which the compiler can't see. Why can't the compiler see? Because c2 is of compile time type Cake.



          In short, the compiler decides which overload, the runtime decides which implementation.



          Responding to your statement:




          if the object is of type ChocolateCake ...




          Only you know the object is of type ChocolateCake. The compiler does not. It only knows c2 is of type Cake because that's what its declaration says.






          share|improve this answer

























            9












            9








            9







            This is because Java uses both static and dynamic binding to choose a method to call in this case.



            The line in question is this, right?



            c2.taste(cc);


            The compiler first chooses which method to call (static binding). Since c2 is of compile time type Cake, the compiler only sees the taste(Cake) method. So it says "call taste(Cake)".



            Now at runtime, the runtime needs to choose which implementation of taste(Cake) to call, depending on the runtime type of c2. This is dynamic binding. Does it choose the one in Cake? Or the one in ChocolateCake? Since c2 is of runtime type ChocolateCake, it calls the implementation of taste(Cake) in ChocolateCake.



            As you can see, the method that you thought would be called - taste(ChocolateCake) - is not even mentioned! This is because that is a different overload of the taste method, and because it is in the ChocolateCake class, which the compiler can't see. Why can't the compiler see? Because c2 is of compile time type Cake.



            In short, the compiler decides which overload, the runtime decides which implementation.



            Responding to your statement:




            if the object is of type ChocolateCake ...




            Only you know the object is of type ChocolateCake. The compiler does not. It only knows c2 is of type Cake because that's what its declaration says.






            share|improve this answer













            This is because Java uses both static and dynamic binding to choose a method to call in this case.



            The line in question is this, right?



            c2.taste(cc);


            The compiler first chooses which method to call (static binding). Since c2 is of compile time type Cake, the compiler only sees the taste(Cake) method. So it says "call taste(Cake)".



            Now at runtime, the runtime needs to choose which implementation of taste(Cake) to call, depending on the runtime type of c2. This is dynamic binding. Does it choose the one in Cake? Or the one in ChocolateCake? Since c2 is of runtime type ChocolateCake, it calls the implementation of taste(Cake) in ChocolateCake.



            As you can see, the method that you thought would be called - taste(ChocolateCake) - is not even mentioned! This is because that is a different overload of the taste method, and because it is in the ChocolateCake class, which the compiler can't see. Why can't the compiler see? Because c2 is of compile time type Cake.



            In short, the compiler decides which overload, the runtime decides which implementation.



            Responding to your statement:




            if the object is of type ChocolateCake ...




            Only you know the object is of type ChocolateCake. The compiler does not. It only knows c2 is of type Cake because that's what its declaration says.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 30 at 18:15









            SweeperSweeper

            72.4k1075144




            72.4k1075144























                8














                Since the reference type of the c2 variable is Cake the taste method having the Cake type parameter will be called.



                This is because the Cake type does not have the taste method which takes a ChocolateCake instance, so you can't invoke that method from a Cake type reference variable.



                Now secondly, in Java due to the mechanism of runtime polymorphism the overridden taste method of the ChocolateCake is being called instead of the version declared in the parent Cake class. This is due to fact at runtime the object which the Cake reference is pointing to, will be examined and the taste version of that particular instance will be invoked.



                So due to the combination of these two effects you see that output.



                If you change the reference type of c2 to ChocolateCake you would see that the output is:



                In taste (ChocolateCake version) of ChocolateCake class 


                when you invoke c2.taste(cc);, since now both the compiler and runtime agrees to call that taste(ChocolateCake cc) method in particular.






                share|improve this answer





























                  8














                  Since the reference type of the c2 variable is Cake the taste method having the Cake type parameter will be called.



                  This is because the Cake type does not have the taste method which takes a ChocolateCake instance, so you can't invoke that method from a Cake type reference variable.



                  Now secondly, in Java due to the mechanism of runtime polymorphism the overridden taste method of the ChocolateCake is being called instead of the version declared in the parent Cake class. This is due to fact at runtime the object which the Cake reference is pointing to, will be examined and the taste version of that particular instance will be invoked.



                  So due to the combination of these two effects you see that output.



                  If you change the reference type of c2 to ChocolateCake you would see that the output is:



                  In taste (ChocolateCake version) of ChocolateCake class 


                  when you invoke c2.taste(cc);, since now both the compiler and runtime agrees to call that taste(ChocolateCake cc) method in particular.






                  share|improve this answer



























                    8












                    8








                    8







                    Since the reference type of the c2 variable is Cake the taste method having the Cake type parameter will be called.



                    This is because the Cake type does not have the taste method which takes a ChocolateCake instance, so you can't invoke that method from a Cake type reference variable.



                    Now secondly, in Java due to the mechanism of runtime polymorphism the overridden taste method of the ChocolateCake is being called instead of the version declared in the parent Cake class. This is due to fact at runtime the object which the Cake reference is pointing to, will be examined and the taste version of that particular instance will be invoked.



                    So due to the combination of these two effects you see that output.



                    If you change the reference type of c2 to ChocolateCake you would see that the output is:



                    In taste (ChocolateCake version) of ChocolateCake class 


                    when you invoke c2.taste(cc);, since now both the compiler and runtime agrees to call that taste(ChocolateCake cc) method in particular.






                    share|improve this answer















                    Since the reference type of the c2 variable is Cake the taste method having the Cake type parameter will be called.



                    This is because the Cake type does not have the taste method which takes a ChocolateCake instance, so you can't invoke that method from a Cake type reference variable.



                    Now secondly, in Java due to the mechanism of runtime polymorphism the overridden taste method of the ChocolateCake is being called instead of the version declared in the parent Cake class. This is due to fact at runtime the object which the Cake reference is pointing to, will be examined and the taste version of that particular instance will be invoked.



                    So due to the combination of these two effects you see that output.



                    If you change the reference type of c2 to ChocolateCake you would see that the output is:



                    In taste (ChocolateCake version) of ChocolateCake class 


                    when you invoke c2.taste(cc);, since now both the compiler and runtime agrees to call that taste(ChocolateCake cc) method in particular.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Mar 30 at 18:12

























                    answered Mar 30 at 18:06









                    Amardeep BhowmickAmardeep Bhowmick

                    5,45821128




                    5,45821128





















                        0














                        In Java the decision which methodset to call in case of c2.taste(cc) is performed at compile-time based on the compile-time type of c2. The compile-time type of c2 is Cake, which means that any method call on c2 is searching just class Cake and its superclasses, and isn't searching any subclasses of Cake (namely ChocolateCake) even if all the subclasses are visible to the compiler.



                        Languages performing fully dynamic method resolution at runtime based on the actual runtime types of the receiver&arguments, which would make c2.taste(cc) be resolved into ChocolateCake.taste(ChocolateCake cc), are rare because it negatively affects runtime performance.






                        share|improve this answer



























                          0














                          In Java the decision which methodset to call in case of c2.taste(cc) is performed at compile-time based on the compile-time type of c2. The compile-time type of c2 is Cake, which means that any method call on c2 is searching just class Cake and its superclasses, and isn't searching any subclasses of Cake (namely ChocolateCake) even if all the subclasses are visible to the compiler.



                          Languages performing fully dynamic method resolution at runtime based on the actual runtime types of the receiver&arguments, which would make c2.taste(cc) be resolved into ChocolateCake.taste(ChocolateCake cc), are rare because it negatively affects runtime performance.






                          share|improve this answer

























                            0












                            0








                            0







                            In Java the decision which methodset to call in case of c2.taste(cc) is performed at compile-time based on the compile-time type of c2. The compile-time type of c2 is Cake, which means that any method call on c2 is searching just class Cake and its superclasses, and isn't searching any subclasses of Cake (namely ChocolateCake) even if all the subclasses are visible to the compiler.



                            Languages performing fully dynamic method resolution at runtime based on the actual runtime types of the receiver&arguments, which would make c2.taste(cc) be resolved into ChocolateCake.taste(ChocolateCake cc), are rare because it negatively affects runtime performance.






                            share|improve this answer













                            In Java the decision which methodset to call in case of c2.taste(cc) is performed at compile-time based on the compile-time type of c2. The compile-time type of c2 is Cake, which means that any method call on c2 is searching just class Cake and its superclasses, and isn't searching any subclasses of Cake (namely ChocolateCake) even if all the subclasses are visible to the compiler.



                            Languages performing fully dynamic method resolution at runtime based on the actual runtime types of the receiver&arguments, which would make c2.taste(cc) be resolved into ChocolateCake.taste(ChocolateCake cc), are rare because it negatively affects runtime performance.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 31 at 15:05









                            atomsymbolatomsymbol

                            21659




                            21659



























                                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%2f55434188%2funclear-about-dynamic-binding%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

                                Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

                                Tähtien Talli Jäsenet | Lähteet | NavigointivalikkoSuomen Hippos – Tähtien Talli

                                Do these cracks on my tires look bad? The Next CEO of Stack OverflowDry rot tire should I replace?Having to replace tiresFishtailed so easily? Bad tires? ABS?Filling the tires with something other than air, to avoid puncture hassles?Used Michelin tires safe to install?Do these tyre cracks necessitate replacement?Rumbling noise: tires or mechanicalIs it possible to fix noisy feathered tires?Are bad winter tires still better than summer tires in winter?Torque converter failure - Related to replacing only 2 tires?Why use snow tires on all 4 wheels on 2-wheel-drive cars?