What's wrong with overridable method calls in constructors?

后端 未结 7 1901
谎友^
谎友^ 2020-11-21 04:53

I have a Wicket page class that sets the page title depending on the result of an abstract method.

public abstract class BasicPage extends WebPage {

    pub         


        
7条回答
  •  别跟我提以往
    2020-11-21 05:05

    Here is an example that reveals the logical problems that can occur when calling an overridable method in the super constructor.

    class A {
    
        protected int minWeeklySalary;
        protected int maxWeeklySalary;
    
        protected static final int MIN = 1000;
        protected static final int MAX = 2000;
    
        public A() {
            setSalaryRange();
        }
    
        protected void setSalaryRange() {
            throw new RuntimeException("not implemented");
        }
    
        public void pr() {
            System.out.println("minWeeklySalary: " + minWeeklySalary);
            System.out.println("maxWeeklySalary: " + maxWeeklySalary);
        }
    }
    
    class B extends A {
    
        private int factor = 1;
    
        public B(int _factor) {
            this.factor = _factor;
        }
    
        @Override
        protected void setSalaryRange() {
            this.minWeeklySalary = MIN * this.factor;
            this.maxWeeklySalary = MAX * this.factor;
        }
    }
    
    public static void main(String[] args) {
        B b = new B(2);
        b.pr();
    }
    

    The result would actually be:

    minWeeklySalary: 0

    maxWeeklySalary: 0

    This is because the constructor of class B first calls the constructor of class A, where the overridable method inside B gets executed. But inside the method we are using the instance variable factor which has not yet been initialized (because the constructor of A has not yet finished), thus factor is 0 and not 1 and definitely not 2 (the thing that the programmer might think it will be). Imagine how hard would be to track an error if the calculation logic was ten times more twisted.

    I hope that would help someone.

提交回复
热议问题