What's wrong with overridable method calls in constructors?

后端 未结 7 1909
谎友^
谎友^ 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:25

    Here's an example which helps to understand this:

    public class Main {
        static abstract class A {
            abstract void foo();
            A() {
                System.out.println("Constructing A");
                foo();
            }
        }
    
        static class C extends A {
            C() { 
                System.out.println("Constructing C");
            }
            void foo() { 
                System.out.println("Using C"); 
            }
        }
    
        public static void main(String[] args) {
            C c = new C(); 
        }
    }
    

    If you run this code, you get the following output:

    Constructing A
    Using C
    Constructing C
    

    You see? foo() makes use of C before C's constructor has been run. If foo() requires C to have a defined state (i.e. the constructor has finished), then it will encounter an undefined state in C and things might break. And since you can't know in A what the overwritten foo() expects, you get a warning.

    0 讨论(0)
提交回复
热议问题