The difference between polymorphism and C + + polymorphism in Java

Source: Internet
Author: User

Source: http://blog.csdn.net/hihui/article/details/8604779

  1. #include <stdio.h>
  2. Class Base
  3. {
  4. Public
  5. int i;
  6. Base ()
  7. {
  8. i = 99;
  9. Amethod ();
  10. }
  11. virtual void Amethod ()
  12. {
  13. printf ("Base.amethod () \ n");
  14. }
  15. };
  16. Class Derived: Public Base
  17. {
  18. Public
  19. int i;
  20. Derived () {
  21. i =-1;
  22. }
  23. virtual void Amethod ()
  24. {
  25. printf ("Derived.amethod () \ n");
  26. }
  27. };
  28. int main (int argc, char *argv[])
  29. {
  30. Base *b = new Derived ();
  31. printf ("%d\n", b->i);
  32. B->amethod ();
  33. }




The output is:

Base.amethod ()
99
Derived.amethod ()

The same Java code

[Java]View Plaincopy
  1. Class Base
  2. {
  3. int i = 99;
  4. public void Amethod ()
  5. {
  6. System.out.println ("Base.amethod ()");
  7. }
  8. Base ()
  9. {
  10. Amethod ();
  11. }
  12. }
  13. Class Derived extends Base
  14. {
  15. int i =-1;
  16. public void Amethod ()
  17. {
  18. System.out.println ("Derived.amethod ()");
  19. }
  20. public static void Main (String argv[])
  21. {
  22. Base B = new Derived ();
  23. System.out.println (B.I);
  24. B.amethod ();
  25. }
  26. }


It outputs the result of

Derived.amethod ()
99
Derived.amethod ()

The difference is reflected in the first line of output;

This line is output in the derived constructor, derived itself does not have a constructor, it only calls the parent class's constructor, that is, Base's Amethod ();

For C + + code, the execution is Base::amethod ();

For Java code, the execution is Derived::amthod ();

Why, when calling the base class's Amethod in C + +, the subclass is not ready yet, so the amethod of the base class is executed.

The difference between polymorphism and C + + polymorphism in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.