Java minefield? Be careful with child and parent class code!

Table of contents

A piece of code that the child and parent classes call the rewrite

1. Rewritten code

2. Execution results

3. Analyze the reasons

4. Summary


A piece of code that the child and parent classes call the rewrite

This is a piece of codewith pitfalls. We create a subclass A and a parent class B, override the function method in A, and Call function in B's constructor

1. Rewritten code

class B{
    public B(){
        function();//啥也不做
    }

    public void function(){
        System.out.println("B.function()");
    }
}


class A extends B{
    private int num = 10086;
    @Override
    public void function(){
        System.out.println("A.function()" + num);
    }
}


public class Main {
    public static void main(String[] args) {
        A a = new A();
    }
}

2. Execution results

3. Analyze the reasons

First, when constructing object A, the constructor method of B will be called. 

Then, the function method is called in the constructor of B. At this time, dynamic binding will be triggered, causing the function in A to be called.

Next, the A object itself has not yet been constructed at this time, and num at this time is still in an uninitialized state, and the value defaults to 0.

Finally, print it outA.function()0

4. Summary

 Summary: We should try toavoidusing (except final and private< a i=9>method). Dynamic binding also occurs when methods with the same name of the parent class and subclass are called in the constructor of the parent class. "Use the simplest way possible to bring the object into a working state" and try not to call methods in the constructor (If the method is overridden by a subclass, it will be triggered. Dynamic binding, but the subclass object has not yet been constructed at this time), there may be some hidden problems that are extremely difficult to find. The above example is relatively simple. If it is a large code, it will It's hard to pinpoint the problem.

Guess you like

Origin blog.csdn.net/A1546553960/article/details/134395195