Override “private” method in java












8















There something ambiguous about this idea and I need some clarifications.



My problem is when using this code:



public class B {

private void don() {
System.out.println("hoho private");
}
public static void main(String args) {
B t = new A();
t.don();
}
}

class A extends B {
public void don() {
System.out.println("hoho public");
}
}


The output is hoho private.



Is this because the main function is in the same class as the method don, or because of overriding?



I have read this idea in a book, and when I put the main function in another class I get a compiler error.










share|improve this question




















  • 1





    Some good reading: stackoverflow.com/questions/2000137/…

    – CollinD
    Jan 22 '16 at 3:35






  • 1





    you are hiding and not overriding.

    – Rahul
    Jan 22 '16 at 3:37






  • 1





    In addition to not be visible outside the type (and perhaps more relevant to the question here), private methods are not polymorphic - only the method defined on the type of the expression will ever be invoked; no dynamic dispatch occurs. In the shown example, the t expression is of type B and thus t.don() will always be invoking B's don. The run-time type A is irrelevant and no 'overriding' of such a private method is allowed.

    – user2864740
    Jan 22 '16 at 3:46













  • then how this works even the subclass object is assigned to subclass reference it still calls parent class private method

    – amarnath harish
    Jun 8 '18 at 7:35


















8















There something ambiguous about this idea and I need some clarifications.



My problem is when using this code:



public class B {

private void don() {
System.out.println("hoho private");
}
public static void main(String args) {
B t = new A();
t.don();
}
}

class A extends B {
public void don() {
System.out.println("hoho public");
}
}


The output is hoho private.



Is this because the main function is in the same class as the method don, or because of overriding?



I have read this idea in a book, and when I put the main function in another class I get a compiler error.










share|improve this question




















  • 1





    Some good reading: stackoverflow.com/questions/2000137/…

    – CollinD
    Jan 22 '16 at 3:35






  • 1





    you are hiding and not overriding.

    – Rahul
    Jan 22 '16 at 3:37






  • 1





    In addition to not be visible outside the type (and perhaps more relevant to the question here), private methods are not polymorphic - only the method defined on the type of the expression will ever be invoked; no dynamic dispatch occurs. In the shown example, the t expression is of type B and thus t.don() will always be invoking B's don. The run-time type A is irrelevant and no 'overriding' of such a private method is allowed.

    – user2864740
    Jan 22 '16 at 3:46













  • then how this works even the subclass object is assigned to subclass reference it still calls parent class private method

    – amarnath harish
    Jun 8 '18 at 7:35
















8












8








8


2






There something ambiguous about this idea and I need some clarifications.



My problem is when using this code:



public class B {

private void don() {
System.out.println("hoho private");
}
public static void main(String args) {
B t = new A();
t.don();
}
}

class A extends B {
public void don() {
System.out.println("hoho public");
}
}


The output is hoho private.



Is this because the main function is in the same class as the method don, or because of overriding?



I have read this idea in a book, and when I put the main function in another class I get a compiler error.










share|improve this question
















There something ambiguous about this idea and I need some clarifications.



My problem is when using this code:



public class B {

private void don() {
System.out.println("hoho private");
}
public static void main(String args) {
B t = new A();
t.don();
}
}

class A extends B {
public void don() {
System.out.println("hoho public");
}
}


The output is hoho private.



Is this because the main function is in the same class as the method don, or because of overriding?



I have read this idea in a book, and when I put the main function in another class I get a compiler error.







java






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 22 '16 at 3:39









Chris Martin

23.7k450106




23.7k450106










asked Jan 22 '16 at 3:33









basel manbasel man

6117




6117








  • 1





    Some good reading: stackoverflow.com/questions/2000137/…

    – CollinD
    Jan 22 '16 at 3:35






  • 1





    you are hiding and not overriding.

    – Rahul
    Jan 22 '16 at 3:37






  • 1





    In addition to not be visible outside the type (and perhaps more relevant to the question here), private methods are not polymorphic - only the method defined on the type of the expression will ever be invoked; no dynamic dispatch occurs. In the shown example, the t expression is of type B and thus t.don() will always be invoking B's don. The run-time type A is irrelevant and no 'overriding' of such a private method is allowed.

    – user2864740
    Jan 22 '16 at 3:46













  • then how this works even the subclass object is assigned to subclass reference it still calls parent class private method

    – amarnath harish
    Jun 8 '18 at 7:35
















  • 1





    Some good reading: stackoverflow.com/questions/2000137/…

    – CollinD
    Jan 22 '16 at 3:35






  • 1





    you are hiding and not overriding.

    – Rahul
    Jan 22 '16 at 3:37






  • 1





    In addition to not be visible outside the type (and perhaps more relevant to the question here), private methods are not polymorphic - only the method defined on the type of the expression will ever be invoked; no dynamic dispatch occurs. In the shown example, the t expression is of type B and thus t.don() will always be invoking B's don. The run-time type A is irrelevant and no 'overriding' of such a private method is allowed.

    – user2864740
    Jan 22 '16 at 3:46













  • then how this works even the subclass object is assigned to subclass reference it still calls parent class private method

    – amarnath harish
    Jun 8 '18 at 7:35










1




1





Some good reading: stackoverflow.com/questions/2000137/…

– CollinD
Jan 22 '16 at 3:35





Some good reading: stackoverflow.com/questions/2000137/…

– CollinD
Jan 22 '16 at 3:35




1




1





you are hiding and not overriding.

– Rahul
Jan 22 '16 at 3:37





you are hiding and not overriding.

– Rahul
Jan 22 '16 at 3:37




1




1





In addition to not be visible outside the type (and perhaps more relevant to the question here), private methods are not polymorphic - only the method defined on the type of the expression will ever be invoked; no dynamic dispatch occurs. In the shown example, the t expression is of type B and thus t.don() will always be invoking B's don. The run-time type A is irrelevant and no 'overriding' of such a private method is allowed.

– user2864740
Jan 22 '16 at 3:46







In addition to not be visible outside the type (and perhaps more relevant to the question here), private methods are not polymorphic - only the method defined on the type of the expression will ever be invoked; no dynamic dispatch occurs. In the shown example, the t expression is of type B and thus t.don() will always be invoking B's don. The run-time type A is irrelevant and no 'overriding' of such a private method is allowed.

– user2864740
Jan 22 '16 at 3:46















then how this works even the subclass object is assigned to subclass reference it still calls parent class private method

– amarnath harish
Jun 8 '18 at 7:35







then how this works even the subclass object is assigned to subclass reference it still calls parent class private method

– amarnath harish
Jun 8 '18 at 7:35














5 Answers
5






active

oldest

votes


















9














You cannot override a private method. It isn't visible if you cast A to B. You can override a protected method, but that isn't what you're doing here (and yes, here if you move your main to A then you would get the other method. I would recommend the @Override annotation when you intend to override,



class A extends B {
@Override
public void don() { // <-- will not compile if don is private in B.
System.out.println("hoho public");
}
}



In this case why didn't compiler provide an error for using t.don() which is private?




The Java Tutorials: Predefined Annotation Types says (in part)




While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.







share|improve this answer


























  • Thank you Elliott, but how the main function can use t.don() while it is a private method inside the class B

    – basel man
    Jan 22 '16 at 7:33






  • 1





    @basel Because it is in class B. Every function in class B can access the private methods in class B.

    – Elliott Frisch
    Jan 22 '16 at 13:24











  • ok thank you very much

    – basel man
    Jan 22 '16 at 23:49



















4














You can't override a private method, but you can introduce one in a derived class without a problem. The derive class can not access the private method on the ancestor.



Since t is a on object of type B, calling don() method will invoque the method defined at B. It doesn't even know that there is a method named also don() at class A






share|improve this answer































    4














    No, a private method cannot be overridden since it is not visible from any other class. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class.






    share|improve this answer































      4















      is this because the main function is in the same class as the method "don"




      No, it's because A's don() is unrelated to B's don() method, in spite of having the same name and argument list. private methods are hidden inside their class. They cannot be invoked directly by outside callers, such as main method in your case, because they are encapsulated inside the class. They do not participate in method overrides.






      share|improve this answer
























      • in this case then why the compiler didnt give compile error for using t.don() which is private??

        – basel man
        Jan 22 '16 at 4:48



















      2














      private members aren't visible to any other classes, even children



      You can't override a private method, but then again, you can't call it either. You can create an identical method with the same name in the child however.



      public class A
      {
      private int calculate() {return 1;}
      public void visibleMethod()
      {
      System.out.println(calculate());
      };
      }

      public class B extends A
      {
      private int calculate() {return 2;}
      public void visibleMethod()
      {
      System.out.println(calculate());
      };
      }


      If you call A.visibleMethod() it prints out 1.



      If you call B.visibleMethod() it prints 2.



      If you don't implement the private calculate() method in B, it won't compile because the public method that calls it can't see the private method in A.






      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%2f34938540%2foverride-private-method-in-java%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        5 Answers
        5






        active

        oldest

        votes








        5 Answers
        5






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        9














        You cannot override a private method. It isn't visible if you cast A to B. You can override a protected method, but that isn't what you're doing here (and yes, here if you move your main to A then you would get the other method. I would recommend the @Override annotation when you intend to override,



        class A extends B {
        @Override
        public void don() { // <-- will not compile if don is private in B.
        System.out.println("hoho public");
        }
        }



        In this case why didn't compiler provide an error for using t.don() which is private?




        The Java Tutorials: Predefined Annotation Types says (in part)




        While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.







        share|improve this answer


























        • Thank you Elliott, but how the main function can use t.don() while it is a private method inside the class B

          – basel man
          Jan 22 '16 at 7:33






        • 1





          @basel Because it is in class B. Every function in class B can access the private methods in class B.

          – Elliott Frisch
          Jan 22 '16 at 13:24











        • ok thank you very much

          – basel man
          Jan 22 '16 at 23:49
















        9














        You cannot override a private method. It isn't visible if you cast A to B. You can override a protected method, but that isn't what you're doing here (and yes, here if you move your main to A then you would get the other method. I would recommend the @Override annotation when you intend to override,



        class A extends B {
        @Override
        public void don() { // <-- will not compile if don is private in B.
        System.out.println("hoho public");
        }
        }



        In this case why didn't compiler provide an error for using t.don() which is private?




        The Java Tutorials: Predefined Annotation Types says (in part)




        While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.







        share|improve this answer


























        • Thank you Elliott, but how the main function can use t.don() while it is a private method inside the class B

          – basel man
          Jan 22 '16 at 7:33






        • 1





          @basel Because it is in class B. Every function in class B can access the private methods in class B.

          – Elliott Frisch
          Jan 22 '16 at 13:24











        • ok thank you very much

          – basel man
          Jan 22 '16 at 23:49














        9












        9








        9







        You cannot override a private method. It isn't visible if you cast A to B. You can override a protected method, but that isn't what you're doing here (and yes, here if you move your main to A then you would get the other method. I would recommend the @Override annotation when you intend to override,



        class A extends B {
        @Override
        public void don() { // <-- will not compile if don is private in B.
        System.out.println("hoho public");
        }
        }



        In this case why didn't compiler provide an error for using t.don() which is private?




        The Java Tutorials: Predefined Annotation Types says (in part)




        While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.







        share|improve this answer















        You cannot override a private method. It isn't visible if you cast A to B. You can override a protected method, but that isn't what you're doing here (and yes, here if you move your main to A then you would get the other method. I would recommend the @Override annotation when you intend to override,



        class A extends B {
        @Override
        public void don() { // <-- will not compile if don is private in B.
        System.out.println("hoho public");
        }
        }



        In this case why didn't compiler provide an error for using t.don() which is private?




        The Java Tutorials: Predefined Annotation Types says (in part)




        While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.








        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 22 '16 at 5:04

























        answered Jan 22 '16 at 3:38









        Elliott FrischElliott Frisch

        153k1389178




        153k1389178













        • Thank you Elliott, but how the main function can use t.don() while it is a private method inside the class B

          – basel man
          Jan 22 '16 at 7:33






        • 1





          @basel Because it is in class B. Every function in class B can access the private methods in class B.

          – Elliott Frisch
          Jan 22 '16 at 13:24











        • ok thank you very much

          – basel man
          Jan 22 '16 at 23:49



















        • Thank you Elliott, but how the main function can use t.don() while it is a private method inside the class B

          – basel man
          Jan 22 '16 at 7:33






        • 1





          @basel Because it is in class B. Every function in class B can access the private methods in class B.

          – Elliott Frisch
          Jan 22 '16 at 13:24











        • ok thank you very much

          – basel man
          Jan 22 '16 at 23:49

















        Thank you Elliott, but how the main function can use t.don() while it is a private method inside the class B

        – basel man
        Jan 22 '16 at 7:33





        Thank you Elliott, but how the main function can use t.don() while it is a private method inside the class B

        – basel man
        Jan 22 '16 at 7:33




        1




        1





        @basel Because it is in class B. Every function in class B can access the private methods in class B.

        – Elliott Frisch
        Jan 22 '16 at 13:24





        @basel Because it is in class B. Every function in class B can access the private methods in class B.

        – Elliott Frisch
        Jan 22 '16 at 13:24













        ok thank you very much

        – basel man
        Jan 22 '16 at 23:49





        ok thank you very much

        – basel man
        Jan 22 '16 at 23:49













        4














        You can't override a private method, but you can introduce one in a derived class without a problem. The derive class can not access the private method on the ancestor.



        Since t is a on object of type B, calling don() method will invoque the method defined at B. It doesn't even know that there is a method named also don() at class A






        share|improve this answer




























          4














          You can't override a private method, but you can introduce one in a derived class without a problem. The derive class can not access the private method on the ancestor.



          Since t is a on object of type B, calling don() method will invoque the method defined at B. It doesn't even know that there is a method named also don() at class A






          share|improve this answer


























            4












            4








            4







            You can't override a private method, but you can introduce one in a derived class without a problem. The derive class can not access the private method on the ancestor.



            Since t is a on object of type B, calling don() method will invoque the method defined at B. It doesn't even know that there is a method named also don() at class A






            share|improve this answer













            You can't override a private method, but you can introduce one in a derived class without a problem. The derive class can not access the private method on the ancestor.



            Since t is a on object of type B, calling don() method will invoque the method defined at B. It doesn't even know that there is a method named also don() at class A







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 22 '16 at 3:39









            Manuel ViedaManuel Vieda

            190410




            190410























                4














                No, a private method cannot be overridden since it is not visible from any other class. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class.






                share|improve this answer




























                  4














                  No, a private method cannot be overridden since it is not visible from any other class. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class.






                  share|improve this answer


























                    4












                    4








                    4







                    No, a private method cannot be overridden since it is not visible from any other class. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class.






                    share|improve this answer













                    No, a private method cannot be overridden since it is not visible from any other class. You have declared a new method for your subclass that has no relation to the superclass method. One way to look at it is to ask yourself whether it would be legal to write super.func() in the Derived class.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 22 '16 at 3:39









                    Nitin DhomseNitin Dhomse

                    1,9641720




                    1,9641720























                        4















                        is this because the main function is in the same class as the method "don"




                        No, it's because A's don() is unrelated to B's don() method, in spite of having the same name and argument list. private methods are hidden inside their class. They cannot be invoked directly by outside callers, such as main method in your case, because they are encapsulated inside the class. They do not participate in method overrides.






                        share|improve this answer
























                        • in this case then why the compiler didnt give compile error for using t.don() which is private??

                          – basel man
                          Jan 22 '16 at 4:48
















                        4















                        is this because the main function is in the same class as the method "don"




                        No, it's because A's don() is unrelated to B's don() method, in spite of having the same name and argument list. private methods are hidden inside their class. They cannot be invoked directly by outside callers, such as main method in your case, because they are encapsulated inside the class. They do not participate in method overrides.






                        share|improve this answer
























                        • in this case then why the compiler didnt give compile error for using t.don() which is private??

                          – basel man
                          Jan 22 '16 at 4:48














                        4












                        4








                        4








                        is this because the main function is in the same class as the method "don"




                        No, it's because A's don() is unrelated to B's don() method, in spite of having the same name and argument list. private methods are hidden inside their class. They cannot be invoked directly by outside callers, such as main method in your case, because they are encapsulated inside the class. They do not participate in method overrides.






                        share|improve this answer














                        is this because the main function is in the same class as the method "don"




                        No, it's because A's don() is unrelated to B's don() method, in spite of having the same name and argument list. private methods are hidden inside their class. They cannot be invoked directly by outside callers, such as main method in your case, because they are encapsulated inside the class. They do not participate in method overrides.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jan 22 '16 at 3:41









                        dasblinkenlightdasblinkenlight

                        611k587751196




                        611k587751196













                        • in this case then why the compiler didnt give compile error for using t.don() which is private??

                          – basel man
                          Jan 22 '16 at 4:48



















                        • in this case then why the compiler didnt give compile error for using t.don() which is private??

                          – basel man
                          Jan 22 '16 at 4:48

















                        in this case then why the compiler didnt give compile error for using t.don() which is private??

                        – basel man
                        Jan 22 '16 at 4:48





                        in this case then why the compiler didnt give compile error for using t.don() which is private??

                        – basel man
                        Jan 22 '16 at 4:48











                        2














                        private members aren't visible to any other classes, even children



                        You can't override a private method, but then again, you can't call it either. You can create an identical method with the same name in the child however.



                        public class A
                        {
                        private int calculate() {return 1;}
                        public void visibleMethod()
                        {
                        System.out.println(calculate());
                        };
                        }

                        public class B extends A
                        {
                        private int calculate() {return 2;}
                        public void visibleMethod()
                        {
                        System.out.println(calculate());
                        };
                        }


                        If you call A.visibleMethod() it prints out 1.



                        If you call B.visibleMethod() it prints 2.



                        If you don't implement the private calculate() method in B, it won't compile because the public method that calls it can't see the private method in A.






                        share|improve this answer




























                          2














                          private members aren't visible to any other classes, even children



                          You can't override a private method, but then again, you can't call it either. You can create an identical method with the same name in the child however.



                          public class A
                          {
                          private int calculate() {return 1;}
                          public void visibleMethod()
                          {
                          System.out.println(calculate());
                          };
                          }

                          public class B extends A
                          {
                          private int calculate() {return 2;}
                          public void visibleMethod()
                          {
                          System.out.println(calculate());
                          };
                          }


                          If you call A.visibleMethod() it prints out 1.



                          If you call B.visibleMethod() it prints 2.



                          If you don't implement the private calculate() method in B, it won't compile because the public method that calls it can't see the private method in A.






                          share|improve this answer


























                            2












                            2








                            2







                            private members aren't visible to any other classes, even children



                            You can't override a private method, but then again, you can't call it either. You can create an identical method with the same name in the child however.



                            public class A
                            {
                            private int calculate() {return 1;}
                            public void visibleMethod()
                            {
                            System.out.println(calculate());
                            };
                            }

                            public class B extends A
                            {
                            private int calculate() {return 2;}
                            public void visibleMethod()
                            {
                            System.out.println(calculate());
                            };
                            }


                            If you call A.visibleMethod() it prints out 1.



                            If you call B.visibleMethod() it prints 2.



                            If you don't implement the private calculate() method in B, it won't compile because the public method that calls it can't see the private method in A.






                            share|improve this answer













                            private members aren't visible to any other classes, even children



                            You can't override a private method, but then again, you can't call it either. You can create an identical method with the same name in the child however.



                            public class A
                            {
                            private int calculate() {return 1;}
                            public void visibleMethod()
                            {
                            System.out.println(calculate());
                            };
                            }

                            public class B extends A
                            {
                            private int calculate() {return 2;}
                            public void visibleMethod()
                            {
                            System.out.println(calculate());
                            };
                            }


                            If you call A.visibleMethod() it prints out 1.



                            If you call B.visibleMethod() it prints 2.



                            If you don't implement the private calculate() method in B, it won't compile because the public method that calls it can't see the private method in A.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 22 '16 at 3:48









                            Jim WJim W

                            442211




                            442211






























                                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%2f34938540%2foverride-private-method-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

                                Contact image not getting when fetch all contact list from iPhone by CNContact

                                count number of partitions of a set with n elements into k subsets

                                A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks