Is it possible to do computation before super() in the constructor?

前端 未结 7 663
深忆病人
深忆病人 2020-12-23 11:17

Given that I have a class Base that has a single argument constructor with a TextBox object as it\'s argument. If I have a class Simple of the following form:



        
相关标签:
7条回答
  • 2020-12-23 11:51

    Yes, there is a workaround for your simple case. You can create a private constructor that takes TextBox as an argument and call that from your public constructor.

    public class Simple extends Base {
        private Simple(TextBox t) {
            super(t);
            // continue doing stuff with t here
        }
    
        public Simple() {
            this(new TextBox());
        }
    }
    

    For more complicated stuff, you need to use a factory or a static factory method.

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