"First Head Java" page 192 polymorphism related errors

1. Title and source code

Page 192 is a Lianliankan, the code is as follows:

public class A {
    
    
    int var = 7;

    void m1() {
    
    
        System.out.println("A's m1,");
    }

    void m2() {
    
    
        System.out.println("A's m2,");
    }

    void m3() {
    
    
        System.out.println("A's m3,");
    }

}
public class B extends A {
    
    
    @Override
    void m1() {
    
    
        System.out.println("B's m1,");
    }
}

public class C extends B {
    
    
    @Override
    void m3() {
    
    
        System.out.println("C's m3," + (var + 6));
    }
}

The main function is as follows:

public class Demo {
    
    
    public static void main(String[] args) {
    
    
        A a = new A();
        B b = new B();
        C c = new C();
        A a2 = new C();

        b.m1();
        c.m2();
        a.m3();
        System.out.println("-------");

        c.m1();
        c.m2();
        c.m3();
        System.out.println("--------");

        a.m1();
        b.m2();
        c.m3();
        System.out.println("--------");
		//这里书上的输出有问题
        a2.m1();
        a2.m2();
        a2.m3();
    }
}

2. Book answers

The book answer is as follows
Insert picture description here

3. The results of the program

The results are as follows
Insert picture description here

4. Error analysis

The last block should be wrong, analyze it:
(1) a2 uses polymorphism to construct a class C object, and the member method follows the principle of " compiling to the left, execution to the right ".
(2) When a2 call M1 () when the method for finding the method from C, C is not the method, so from C parent class B looking in, B in the rewritten M1 () method, the output B class m1() method, so the output of a2.m1() is B's m1 .
(3) When a2 call M2 () time method, since C is not the method, so from C parent class B looking in B are not, so the B parent class A looking in soThe output of a2.m2() is A's m2 .
(4) When a2 call M3 () when the method C override the M3 () method, so that the output C apos m3,13 .
If what I said is wrong, I hope you can leave a message for guidance, thank you!

Guess you like

Origin blog.csdn.net/weixin_45727931/article/details/108368394