Source: http://blog.csdn.net/hihui/article/details/8604779
- #include <stdio.h>
- Class Base
- {
- Public
- int i;
- Base ()
- {
- i = 99;
- Amethod ();
- }
- virtual void Amethod ()
- {
- printf ("Base.amethod () \ n");
- }
- };
- Class Derived: Public Base
- {
- Public
- int i;
- Derived () {
- i =-1;
- }
- virtual void Amethod ()
- {
- printf ("Derived.amethod () \ n");
- }
- };
- int main (int argc, char *argv[])
- {
- Base *b = new Derived ();
- printf ("%d\n", b->i);
- B->amethod ();
- }
The output is:
Base.amethod ()
99
Derived.amethod ()
The same Java code
[Java]View Plaincopy
- Class Base
- {
- int i = 99;
- public void Amethod ()
- {
- System.out.println ("Base.amethod ()");
- }
- Base ()
- {
- Amethod ();
- }
- }
- Class Derived extends Base
- {
- int i =-1;
- public void Amethod ()
- {
- System.out.println ("Derived.amethod ()");
- }
- public static void Main (String argv[])
- {
- Base B = new Derived ();
- System.out.println (B.I);
- B.amethod ();
- }
- }
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